nested Math.Pow(...) acting weird

c#, math, nested, pow

Solution

Why do you expect:

pow(d23, 2)

to be the same as

pow(23, 2)

?

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

Problem

Currently I'm rewriting some old C++ code to C#. When running some tests it didn't work as it should, and I started debugging, and came across the below which I cant seem to figure out. As I'm doing a lot of math in the class and using Math.Pow function very often, I created a shortcut method for it: ``` public double pow(double d, double p) { return Math.Pow(d,p); } ``` Then I have a code line as follows, which use this method quite some times: ``` 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 didn't give the expected result, so I started splitting it up into smaller pieces as 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 splitting 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 to the same as q5, but it does not. q12 instead evaluates to 4479508755225.0 What's wrong with the code?

Original source