0

I'm trying to make to make a script to help me with my maths

example equation: y=(4*(x*2)^(2x+4))+4*x^2

For this to work, I just need it to understand that only (x*2) needs to be put to the power of (2x+4), and then to sub that back into the original equation, which of course you can just eval() an answer.

I want to calculate the values of y, when I know an x value. This WOULD be relatively easy if it weren't for powers. I just can't get my head round how to do them.

I know you can use pow(), but I'm trying to make a script to work with any equation. So it sort of needs to understand the syntax.

Any suggestions how to go about this?

Jim
  • 18,673
  • 5
  • 49
  • 65
Tom
  • 1,068
  • 2
  • 25
  • 39
  • 3
    I'm not sure I understand the question. Can you clarify why using pow() doesn't solve the problem? – thedayturns Sep 22 '10 at 19:22
  • Are you asking to evaluate a power in PHP, or how to parse a mathematical expression obeying order of operations? – Billy ONeal Sep 22 '10 at 20:06
  • pow() does solve my problem, it's just a case of working out how to implement it, as you may have multiple powers. example: y=((4x)^2)^(4x^2) etc. – Tom Sep 26 '10 at 17:25

4 Answers4

3

For a native PHP sandbox for evaluating formulae, which works as Sjoerd's answer describes, take a look at the evalMath class on PHPClasses.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • There's no cheating in using other people's work when they make that work freely available for people like yourself who need to do the same thing, as long as you give them due credit (and fulfil any terms of license)... that's why Miles Kaufmann posted evalMath on PHPClasses – Mark Baker Sep 26 '10 at 20:45
1

Try implementing a calculator parser. (Linked example is C++ but that should give you the idea. You can add capability to parse ^ for power.)

This will get you part of the way toward what you want. Otherwise, you'll probably want a full-blown symbolic math package if you start getting too complicated with your function types.

John
  • 15,990
  • 10
  • 70
  • 110
1

Also, you should definitely not use eval() to allow users to evaluate numerical expressions. It's a disaster waiting to happen.

Emil H
  • 39,840
  • 10
  • 78
  • 97
1

I once made a calculator script.

  • It parses the calculation and puts each number and operator on a stack, in reverse polish notation.
  • It calculates the results by executing operations all operations on the stack.
Sjoerd
  • 74,049
  • 16
  • 131
  • 175