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

孤者浪人 提交于 2019-12-11 21:12:05

问题


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.


来源:https://stackoverflow.com/questions/3772821/whats-an-easy-way-of-doing-powers-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!