What's an easy way of doing powers in PHP?

2019-09-11 02:44发布

问题:

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:

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



回答2:

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.



回答3:

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



回答4:

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.