pentadecagon
pentadecagon

Reputation: 4847

Precision of floating point operations

Floating point operations are typically approximations to the corresponding arithmetic operations, because in many cases the precise arithmetic result cannot be represented by the internal number format. But what happens if I have a program where all numbers can actually be represented exactly by IEEE 754 single precision? Consider for example this:

float a = 7;
float b = a / 32.0;
float c = a + b;
float d = c - a;
assert( d == b );

Is it safe to assume that within this and similar cases, the result of the numerical calculation is identical to the exact arithmetic result? I think this sort of code would work on every actual machine. Is this correct?

Edit This question is not about what the standard says, but rather about the real world. I'm well aware that in theory one could create a conforming engine where this would fail. I don't care, but rather I wonder if this works on existing machines.

Upvotes: 1

Views: 132

Answers (2)

vonbrand
vonbrand

Reputation: 11831

"Real" machines are quite careful in implementing the standard exactly (just remember the Pentium division bug). But be careful to check, the i386 line of machines did use some extra bits in its registers, which were cut off when asigning to/from memory, so computations done only in registers gave different results than if some intermediate results where spilled to memory.

Also check out David Goldberg's What every computer scientist should know about floating point arithmetic.

In any case, it doesn't make any sense to "round" (or otherwise mangle) a number that can be represented exactly.

Upvotes: 0

user1937198
user1937198

Reputation: 5358

No as the c++ standard does not require floating point values to be stored in the IEEE 754 format.

Upvotes: 2

Related Questions