Source for ASCII to FLOAT
Michael Meissner
meissner at tiktok.dg.com
Thu Jul 27 06:16:07 AEST 1989
In article <38 at pldote.intel.com> jsturges at pldote.intel.com (~Jay Sturges) writes:
|
| /*
| * Here is a routine written some time ago
| * which will perform ASCII to float conversions
| *
| * Enjoy,
| *
| * Jay Sturges sun!sacto!pldote!jsturges
| *
| */
...
| if (!error)
| {
| /*
| * signed exponetial and mantissa
| */
| exp *= esign;
| gtvalue *= dsign;
|
| if (exp > MAXEXP || exp < MINEXP ||
| (exp + big) > MAXEXP ||
| (exp + big) < MINEXP)
| error = TRUE;
| else if (exp > 0)
| while (--exp >= 0)
| gtvalue *= 10.0;
| else if (exp < 0)
| while (++exp <= 0)
| gtvalue *= 0.1;
...
| /*
| * after the decimal point
| */
| dtmp = CVALUE(c);
| if (didx >= MAXEXP)
| { /* too small, it's virtually zero */
| dtmp = 0.0;
| didx = 0;
| }
| while (--didx >= 0) /* C is pass by value */
| dtmp *= 0.1;
| *value += dtmp;
| }
| }
|
This code is subject to round off errors (particularly multiplying by
0.1 which is faster, but less accurate than dividing by 10.). Each
fractional digit increases the accumulated errors. For example, the
following two numbers:
1.0
0.1e1
should be identical down to the last bit. The best way to do this
conversion is to accumulate the mantissa as an integer, possibly
dropping digits when the bits in the mantissa cannot hold the number
exactly. You then calculate the scale factor (exponent - number of
digits not dropped to the right of the decimal point). If this scale
factor is 0, you are done; if it is positive, you multiply by the
appropriate power of ten (which you get from a statically calculated
array, not by repeated multiplications); if it is negative you divide
by the appropriate power of ten (negative of the scale factor). This
way the round off error is minimized to one multiply or divide. A
good course or textbook in numerical analysis should give other means
of preserving the accuracy.
--
Michael Meissner, Data General.
Uucp: ...!mcnc!rti!xyzzy!meissner If compiles were much
Internet: meissner at dg-rtp.DG.COM faster, when would we
Old Internet: meissner%dg-rtp.DG.COM at relay.cs.net have time for netnews?
More information about the Comp.lang.c
mailing list