Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!mcnc!rti!xyzzy!tiktok!meissner From: meissner@tiktok.dg.com (Michael Meissner) Newsgroups: comp.lang.c Subject: Re: Source for ASCII to FLOAT Keywords: atof( ) ASCII float Message-ID: <8207@xyzzy.UUCP> Date: 26 Jul 89 20:16:07 GMT References: <38@pldote.intel.com> Sender: usenet@xyzzy.UUCP Reply-To: meissner@tiktok.UUCP (Michael Meissner) Distribution: usa Organization: Data General (Languages @ Research Triangle Park, NC.) Lines: 75 In article <38@pldote.intel.com> jsturges@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@dg-rtp.DG.COM faster, when would we Old Internet: meissner%dg-rtp.DG.COM@relay.cs.net have time for netnews?