This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Hi Sapna, JLS states " Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod. " So the computation works like a integer modulo operation. For your example: 2.2d is treated as a 2, so the remainder is 2.... Cause its a double you have a "incorrect" value, when displaying it... hope that helps, correct me if i'm wrong Oliver
It has to do with the precision of doubles and floats. Since doubles are not precise numbers like integers, you lose a .00000001 here or there. So you end up with 44d % 2.2d not ever giving you 0 becuase like lakshmi said, it is like writing 44d - 2.2d over and over until you are less than 2.2d. You can try this in a loop like this:
Sapna Mathur
Greenhorn
Joined: Nov 06, 2000
Posts: 8
posted
0
So how can I get an accurate modulus value if I have to use it in a program ? Will it not affect the accuracy of the program if an incorrect value is produced in the beginning of a process?
Originally posted by Sapna Mathur: So how can I get an accurate modulus value if I have to use it in a program ? Will it not affect the accuracy of the program if an incorrect value is produced in the beginning of a process?
You can't. It is to do with the way java stores the floating point numbers internally. You will always get an approximate value while dealing with floating points no matter what operation you perform on them. HTH Shubhangi
Sapna Mathur
Greenhorn
Joined: Nov 06, 2000
Posts: 8
posted
0
Wow. That is amazing. Thanks. Best of luck with your exam.
lakshmi nair
Ranch Hand
Joined: Oct 11, 2000
Posts: 63
posted
0
I just wanted to share some knowledge i gained. There is a method Math.IEEEremainder(double,double) which can give you the a result which can be sometimes equivalent to % operation. Here goes the actual explanation from API.. Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard. The remainder value is mathematically equal to f1 - f2 � n, where n is the mathematical integer closest to the exact mathematical value of the quotient f1/f2, and if two mathematical integers are equally close to f1/f2, then n is the integer that is even. If the remainder is zero, its sign is the same as the sign of the first argument.