Nested Math.Pow (...) acting weird

I am currently rewriting old C ++ code into C #. When running some tests, it did not work as it should, and I started debugging, and came across the lower one, which I apparently can not understand.

Since I do a lot of math in the class and often use the Math.Pow function, I created a shortcut method for it:

public double pow(double d, double p) { return Math.Pow(d,p); } 

Then I have a line of code as follows that use this method quite often:

 double y = pow((pow(d12, 2) + pow(d13, 2) + pow(23, 2)), 2) - (2.0 * (pow(d12, 4) + pow(d13, 4) + pow(d23, 4))); 

This line did not give the expected result, so I started to break it into smaller pieces, since it should be calculated ... for example, the value before the minus sign should be equal to q5:

 double q1 = pow(d12, 2); double q2 = pow(d13, 2); double q3 = pow(d23, 2); double q4 = q1 + q2 + q3; double q5 = pow(q4, 2); 

After these lines, q5 is 8775553070736.0

Then I tried to split the long line into two parts, where the first should be equal to the above 5 lines, just written as one line:

 double q12 = pow((pow(d12, 2) + pow(d13, 2) + pow(23, 2)), 2); 

Which I would expect to evaluate in the same way as q5, but it is not. q12 instead evaluates to 4479508755225.0

What is wrong with the code?

+4
source share
1 answer

Why do you expect:

 pow(d23, 2) 

to be the same as

 pow(23, 2) 

?

PROTIP: In VS always change the color of the default numbers (black), to something else (I like red).

+6
source

Source: https://habr.com/ru/post/1415563/


All Articles