Let's say I've got two integer values stored in double
variables, e. g.:
double x = 100.0;
double y = 7.0;
May I safely assume that any arithmetic operation on these two double variables that would yield an integer result, will return an exact integer value (as a double
)? That is, will for example all of:
x + y = 107.0
x - y = 93.0
x * y = 700.0
return the exact integer values, or will be there some accuracy problems? Like x*y
being 699.99995
or so?
The general question: Is it true that any arithmetic operation on two double variables holding integer values that would yield an integer result will return the exact integer value (as a double)?
I'm asking this in a Java context, but I assume it's similar in other languages, too.
The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).
Arithmetic operations are executed using numeric data. If character string data is specified, arithmetic operations are executed after the character string data is converted to numeric data.
The arithmetic operators for scalars in MATALB are: addition (+), subtraction (−), multiplication (*), division (/), and exponentiation (^). Vector and matrix calculations can also be organized in a simple way using these operators. For example, multiplication of two matrices A and B is expressed as A.
As long as the integer result of your operation can be exactly represented as a double, you will get an exact result, but as soon as the integer result exceeds the number of bits available in the mantissa (i.e. 52+1 = 53 bits), it will be rounded.
In general, the answer is No. However, I strongly recommend reading David Goldberg’s "What Every Computer Scientist Should Know About Floating-Point Arithmetic" - it never hurts to know the things from the inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With