Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nth root of small number return an unexpected result in C#

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 third root of 1.07, I get 1, which is clearly not true.

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

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

How do I solve this problem?

I would guess that this is a floating point arithmetic issue, but I don't know how to handle it.

like image 587
JK. Avatar asked Oct 10 '09 01:10

JK.


2 Answers

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.

like image 77
Yuriy Faktorovich Avatar answered Nov 15 '22 06:11

Yuriy Faktorovich


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 at the wrong nesting level, 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 ...

like image 38
I. J. Kennedy Avatar answered Nov 15 '22 07:11

I. J. Kennedy