davy
davy

Reputation: 4552

Solve 'x' in this equation when passed variables using C#

I want to create a C# method that solves 'x' for the equation below when it is passed with value of a, b, c, d, and e.

0 = (a)(x) + (1-x) [(b)(c)-(d)(e)]

I'm not very mathematically inclined so I don't even know how to get started using something like Math.Net from looking at the documentation.

Can someone please help or point me to an example?

Upvotes: 1

Views: 496

Answers (2)

Patrick87
Patrick87

Reputation: 28292

As the comment mentions, this can be simplified

0 = ax + (1-x)(bc - de)
0 = ax + (bc - de) - x(bc - de)
0 = x(a - (bc - de)) + (bc - de)
-(bc - de) = x(a - (bc - de))
(de - bc) = x(a - bc + de)
x = (de - bc) / (a - bc + de)

That last line works provided a - bc + de is not zero. If it is zero, then look at the nextto last line. We find that any value for x works if de - bc = 0; otherwise, no value for x makes the equation true. In summary:

If a - bc + de = 0 then
    if de - bc = 0 then
        print "any value of x works"
    else
        print "no value of x works"
else
    print (de - bc) / (a - bc + de)

Something like that.

Upvotes: 1

moghya
moghya

Reputation: 864

First, simplify equation in terms of x

0 = (a)(x) + (1-x) [(b)(c)-(d)(e)]
0 = (a)(x) + [(b)(c)-(d)(e)] - [(b)(c)-(d)(e)](x)
0 = (a)(x) - [(b)(c)-(d)(e)](x) + [(b)(c)-(d)(e)]
0 = { (a) - [(b)(c)-(d)(e)] } (x) + [(b)(c)-(d)(e)]
0 = [(a) - (b)(c) + (d)(e)](x) + [(b)(c)-(d)(e)]
- [(b)(c)-(d)(e)] = [(a) - (b)(c) + (d)(e)](x)
[(d)(e)-(b)(c)] = [(a) - (b)(c) + (d)(e)](x)
[(d)(e)-(b)(c)] / [(a) - (b)(c) + (d)(e)] = (x)
(x) = [(d)(e)-(b)(c)] / [(a) - (b)(c) + (d)(e)]
public static float solveForX(int a, int b, int c, int d, int e) {
        return (d*e - b*c)/ (a- b*c + d*e);
    }

Upvotes: 2

Related Questions