Desmond Hume
Desmond Hume

Reputation: 8627

Floating-point division imperfection

I know that the floating-point is not perfect, either it's float or double, but does it mean that, when I divide one floating-point number by another and the the dividend is divisible by the divider without a reminder (like 10000.0 is divisible by 10.0), is it possible that I get a number with .99999999... at the end which is only smaller than the correct result by a tiny fraction. Can such thing happen with floating-points?

I need to know because I need to apply floor function after the division and it would make a huge difference if floating-point divisions are really that imperfect.

Upvotes: 0

Views: 497

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Assuming the hardware is using IEEE 754 floating point division, the key issue is whether the natural number operands are exactly representable.

First of all, the formats have finite range. The natural numbers do not. However, even the 32-bit binary floating point limit, around 10^38, is large enough for most practical purposes.

Within that range, it comes down to whether a natural number can be expressed as 1.x*2^n where n is an integer and 1.x is a binary fraction with no more than 23 bits after the binary point. All natural numbers that fit in 24 bits meet that condition. So do all powers of two that are in range.

In general, larger floats, with bigger exponents, have bigger gaps between consecutive values. Up to 24 bit naturals, the gap is no greater than 1, so all the natural numbers are representable. At the next step, the gap is 2, then 4, then 8 ... as the exponent increases.

Upvotes: 2

Pascal Cuoq
Pascal Cuoq

Reputation: 80335

does it mean that, when I divide one floating-point number by another and the the dividend is divisible by the divider without a reminder (like 10000.0 is divisible by 10.0), it's possible that I get a number with .99999999... at the end

No. IEEE 754 division is correctly rounded. If there is a representable floating-point number (1000 in your example) for the result, this is the result you will get for the division.

What can happen is that you do not divide the numbers you are thinking, because you wrote 0.1 and you think that this represents the mathematical value 0.1. In this case the end result can be surprising, but this is no fault of the floating-point division.

As long that you know that you are dividing the numbers you mean, if the mathematical result of the division is, say, an integer below 224, then the result of the floating-point division will be that integer.

Upvotes: 7

Related Questions