views:

121

answers:

4

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?

+1  A: 

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 at CashCommons
+1  A: 

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

Emil H
+1  A: 

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
RPN is cheating :P
Billy ONeal
+2  A: 

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
Works brilliantly. I just feel like I'm cheating this way! But thanks :)
Tom
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