Re: floating points



From: Ramon Alberto Triay Espinosa <rtriay avantel net>
>
> yep, john is right 85.3 has no exactly binary representation and this is
> a problem in every software/hardware you use. Beside, if what you're
> trying to do is to get an exact internal representation of the float try
> using two integer variables: one for the integer part and other for the
> fractional and parse the user entry looking for the decimal separator
> (point or comma) or, easier but not elegant, use two GtkEntry to get
> each part of it.
>
> SALUDOS!!!
> rtriay
> :)

Another trick along these lines is to use some sort of fixed point
representation. If you know you won't have more than, e.g., two
numbers past the decimal point, then take the float you get
from strtod(), multiply by 100, and round to the nearest int
(add 0.5 and cast to int). You can then get the integer and
fractional parts through integer arithmetic, without worrying
about parsing strings.

Ron Steinke


> El 01 Mar 2002 12:25:20 +0000, John Cupitt ng-london org uk escribi?:
> > Lourdes Maldonado wrote:
> > > I have an entry field where the user enters a string that should 
> > > correspond to a floating point number (an FM frequency).  When I 
> > > retrieve the string from the entry field and convert it (using strtod) 
> > > to a floating point, the number does not come out exact (i.e. if I enter 
> > > the string 85.3 the floating point number I get is 85.299995).
> > 
> > Hi Lourdes, this is because 85.3 does not have an exact binary 
> > representation ... it's a recurring fraction. There's no bug, you really 
> > are getting the most accurate double representation of 85.3, it just 
> > looks a bit ugly.
> > 
> > You can make it prettier by reducing the number of digits you display 
> > when you send the result back to the user. For example:
> > 
> > printf( "%.4g\n", 85.3 );
> > 
> > will print "85.3".
> > 
> > John



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]