Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve a math equation in a programming language?

I need help to solve this formula ((n * 2) + 10) / (n + 1) = 3, preferably in PHP. (The numbers 2, 10 and 3 should be variables that can be changed.)

I'm able to solve this equation on paper quite easily. However, when I try to implement this in PHP, I'm not sure where to start. I've done several Google queries and searches on here and nothing seems to help. I'm missing the proper approach to deal with this problem.

Any tips and pointers would be great, and if you provide the exact code, please explain how you got to this result.

like image 480
xidew Avatar asked Aug 31 '11 07:08

xidew


People also ask

Which programming language is used for solving mathematical problems?

The Mathematical Programming Language (MPL) is a high-level user-oriented programming language intended particularly for develop- ing, testing, and communicating mathematical algorithms.

How do you solve a math equation in Python?

To solve the two equations for the two variables x and y , we'll use SymPy's solve() function. The solve() function takes two arguments, a tuple of the equations (eq1, eq2) and a tuple of the variables to solve for (x, y) . The SymPy solution object is a Python dictionary.

How do you use math in programming?

This field of mathematics is also utilized in a wide array of programming areas such as making visuals or graphs, simulations, coding-in applications, problem-solving applications, analysis and design of algorithms, and making statistic solvers.


2 Answers

You can use http://pear.php.net/package/PHP_ParserGenerator/redirected to parse the math expressions into a syntax tree, then do the maths.

((n * 2) + 10) / (n + 1) = 3 would look like:

enter image description here

The idea is to bring on the right subtree (here ...) all the numbers, and on the left all the unknownws, just as you'd do on paper.

In the end you'll have:

  +
 / \
n  -7

which is 0. And there you have your solution, for any math expression (with one unknown variable).

I'll leave the algorithm to you.

like image 197
Flavius Avatar answered Oct 13 '22 01:10

Flavius


how about using brute-force??!?! might be slow and not exact:

$step = 0.00001;
$err = 0.1; //error margin
$start = 0;
$response = 3;

for($i = $start;$i <= 3;$i += $step){
   if((($i * 2) + 10) / ($i + 1) >= $response - $err){
       echo "the answer is $i";
   }
}

You could improove this answer.. on every loop you could calculate the distance between the current answer and the desired answer, and adjust the parameters acording to that..

This reminds me my old A.I. class =)

Good Luck

like image 24
pleasedontbelong Avatar answered Oct 13 '22 01:10

pleasedontbelong