views:

527

answers:

3

When I try to take the N th root of a small number using C# I get a wrong number.

For example when I try to take the 3rd root of 1.07, I get 1, which is clearly not true.

Here is the exact code I am using to get the 3rd root.

MessageBox.Show(Math.Pow(1.07,(1/3)).toString());

Can anyone tell me how to solve this problem. I would guess that this is a floating point arithmetic issue, but I don't know how to handle it.

Thanks!

+8  A: 

C# is treating the 1 and the 3 as integers, you need to do the following:

Math.Pow(1.07,(1d/3d))

or

Math.Pow(1.07,(1.0/3.0))

It is actually interesting because the implicit widening conversion makes you make a mistake.

Yuriy Faktorovich
+2  A: 

I'm pretty sure the "exact code" you give doesn't compile.

MessageBox.Show(Math.Pow(1.07,(1/3).toString()));

The call to toString is in the wrong case, needs to be ToString, and (1/3) is integer division, which is probably the real problem you're having. (1/3) is 0 and anything to the zeroth power is 1. You need to use (1.0/3.0) or (1d/3d) or ...

I. J. Kennedy
Dear captain sarcastic. Sorry about the misplaced ). I should have copied and pasted instead of retyping. I have now corrected the info. Thank you for the excellent answer!
JK
ps. worked great
JK
I normally wouldn't point out an obvious syntax error but somehow felt obligated since you bothered to use the word "exact". Glad it helped.
I. J. Kennedy
+2  A: 

First things first: if that's the exact code you're using, there's likely something wrong with your compiler :-)

MessageBox.Show(Math.Pow(1.07,(1/3).toString()));

will evaluate (1/3).toString() first then try and raise 1.07 to the power of that string.

I think you mean:

MessageBox.Show(Math.Pow(1.07,(1/3)).ToString());

As to the problem, (1/3) is being treated as an integer division returning 0 and n0 is 1 for all values of n.

You need to force it to a floating point division with something like 1.0/3.0.

paxdiablo
Sorry about the misplaced ). I should have copied and pasted instead of retyping. I have now corrected the info.
JK