Re: fractions and floating point
- From: Lawrence Kirby <lknews@xxxxxxxxxxxxxxx>
- Date: Thu, 14 Jul 2005 12:36:05 +0100
On Thu, 14 Jul 2005 11:32:22 +0200, Steffen wrote:
> Hi,
>
> is it possible to have two fractions, which (mathematically) have the
> order a/b < c/d (a,b,c,d integers), but when (correctly) converted into
> floating point representation just have the opposite order?
They don't have to be integers, but we'll need to assume that we are
talking about values that are exactly representable in the floating point
type (i.e. there is no approximation step before the division takes
place). This isn't the case for all integers in the range of representable
values of a floating point type.
> The idea is that the two fractions are almost identical and that the
> error introduced by going to floating point representation is bigger
> than the exact difference, but different for the two fractions such that
> it somehow turns them around.
The property you want isn't guaranteed by C, but it may well be guaranteed
by IEEE 754 floating point arithmetic. It does follow when inexact
results are always rounded to the nearest representable floating point
value ***when using a consistent precision***. However C allows
intermediate results to be evaluated at a higher precision than the
underlying type represents, and this doesn't have to be consistent. So a/b
could in theory be evaluated at a different precision to c/d, and the
differing rounding that results could cause the ordering to be broken.
> I tried some numbers, but so far it always was ok.
>
> I know that this depends on the way floating points are represented, so
> the more precise question would be: is there a standard that would
> ensure that this never happens? Does somebody have a concrete example
> for a specific platform?
The trouble is that this is VERY dependent on the architecture and the
specific code that the compiler generates. For example on x86 systems
FPU registers are 80 bits (although this is settable) and float and double
values tend to be calcuated and held at a higher precision in registers
than when they are stored in memory. So if the compiler decides to store
one intermediate result in memory but not the other the problem can occur.
Lawrence
.
- References:
- fractions and floating point
- From: Steffen
- fractions and floating point
- Prev by Date: Re: size of multi-dimensional array and qsort
- Next by Date: String Manipulation error
- Previous by thread: Re: fractions and floating point
- Next by thread: Re: fractions and floating point
- Index(es):
Relevant Pages
|