Computer Science Canada

comparing double to integer

Author:  cool dude [ Sun Aug 13, 2006 2:18 pm ]
Post subject:  comparing double to integer

how would i compare a number that is declared as a double although it is an integer that just has a zero at the end. ex: 123.0 to an integer. i can't declare the double number as an integer because i'm using Math.Pow and it always makes it double, but i wanna take the answer from that and see if it equals to an integer number. for example does 123.0 = 123. this will not be equal, thus i will not get any results. any suggestions?

Author:  Justin_ [ Sun Aug 13, 2006 2:49 pm ]
Post subject: 

Have you tried: instead of casting the Math.Pow variable cast the integer you are comparing to a float? Just a suggestion.

(Math.Pow.float_int == (float) int_variable)

Author:  Justin_ [ Sun Aug 13, 2006 2:52 pm ]
Post subject: 

Or wait, I misunderstood. Just cast the double returned from Math.Pow and compare...

if ((int) power_returned == int_)

Author:  wtd [ Sun Aug 13, 2006 2:56 pm ]
Post subject: 

Keep in mind that floating point numbers are inherently imprecise. Thus it can be difficult to directly compare two such numbers for equality.

Author:  r.3volved [ Sun Aug 13, 2006 4:47 pm ]
Post subject: 

also, casting a double to an int will either truncate the decimals or round them...

You would have to cast your integer to a double to compare the two, not visa versa

Author:  bugzpodder [ Sat Sep 16, 2006 8:12 pm ]
Post subject: 

add some epsilon constant to the result and truncate it by casting to an int

Author:  McKenzie [ Tue Sep 19, 2006 11:54 am ]
Post subject: 

Floating point numbers are imprecise only when representing fractions, or extreamely large numbers. Casting it should be fine.

Author:  bugzpodder [ Thu Sep 21, 2006 7:06 pm ]
Post subject: 

http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=integersReals

Author:  bugzpodder [ Thu Sep 21, 2006 7:11 pm ]
Post subject: 

cool! i forgot all about x&(x-1) !! now i can use it to improve my AI Smile


: