Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arithmetic operations on double variables holding integer values exact?

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.

like image 708
MicSim Avatar asked Mar 11 '11 12:03

MicSim


People also ask

Which arithmetic operators can be used in operations with integer numbers?

The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).

What is the data type usually used in arithmetic operation?

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.

Which arithmetic operator is used to multiply two numbers?

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.


2 Answers

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.

like image 107
Sven Marnach Avatar answered Sep 24 '22 12:09

Sven Marnach


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.

like image 40
kervich Avatar answered Sep 23 '22 12:09

kervich