开发者

How to solve a math equation in a programming language?

开发者 https://www.devze.com 2023-04-01 03:29 出处:网络
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 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 Go开发者_高级运维ogle 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.


You're wanting to solve an equation, not implement it. There's a difference. Implementing the equation would be as simple as typing it in. You'd probably want to make it an equality operator (==) though.

Equation solvers are complicated, complicated things. I wouldn't try to make one when there are such good ones ( http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems ) lying around.


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:

How to solve a math equation in a programming language?

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.


<?php

// ((x * n) + y)/(n + 1) = z)
// => n=(y-z)/(z-x)
function eq ($x=0,$y=0,$z=0)
{
    if ($z!=$x)
    {
        $n=($y-$z)/($z-$x);
    } else
    {
        $n='NAN';
    }
    return $n;
}

?>

(My algebra is old and flakey but I think this is right)


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


Here's how to solve that equation in C# with the Symbolism computer algebra library:

var n = new Symbol("n");

(((n * 2) + 10) / (n + 1) == 3)
    .IsolateVariable(n)
    .Disp();

The following is displayed on the console when that code is executed:

n == 7
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号