Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello!

I used this:
C#
double secondnum = Math.Pow(num, 1.0 / 3);
            if (secondnum - (int)secondnum == 0)
            {
                return true;
            }
            else return false;

But, if I check it with this numb:66430125 then it gives 404.99999999999989, and in calculator it gives 405. So How could I solve this one?
Posted
Comments
Dr.Walt Fair, PE 23-Dec-10 21:10pm    
Welcome to the wonderful world of floating point math on limited precision computers!

Floating point Types (double and float) are not exact. You have to do some rounding, for example:
C#
double secondNum = Math.Round(Math.Pow(num, 1.0 / 3), 9);
 
Share this answer
 
Comments
Dalek Dave 23-Dec-10 20:18pm    
Good answer.
Sergey Alexandrovich Kryukov 25-Dec-10 0:20am    
Toli, I don't think rounding can improve accuracy. You just pick a special case when the accuracy looks better after rounding. In average situation, the rounding makes accuracy worse.
It's very bad to do rounding in intermediate result in calculation program, even if you count dollars and cents. Practically, one can create a calculation algorithm yielding any preset relative error.

Don't mix this issue with nice rounding used for textual presentation; this is more about formatting than about real accuracy.

One real purpose of rounding is preparation for conversion to integer; it also used in random number generations, etc.
Ha-ha. This is a correct answer with expected accuracy.
 
Share this answer
 
Comments
Dalek Dave 23-Dec-10 20:18pm    
Close enough for Windows! :)
Espen Harlinn 26-Feb-11 11:10am    
A 40 >> 3 :)
Sergey Alexandrovich Kryukov 26-Feb-11 19:17pm    
Is it shift or "much more"? :-)
--SA
Espen Harlinn 27-Feb-11 4:56am    
An attempt at humor yielding 5 :)
Sergey Alexandrovich Kryukov 1-Mar-11 3:01am    
I maybe need to sleep. Could not even figure out about humor and the humorist...
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900