Parse floats from string speed contest
Can anyone see a faster way to parse floats than this ?
PUB ParseFloat(sptr) :retv | dptr,chr,sign
sign:=0
dptr:=0
retv:=0
repeat
if byte[noparse][[/noparse]sptr] <>" "
quit
sptr++
repeat
chr:=byte[noparse][[/noparse]sptr]
if chr==0
quit
elseif chr=="-"
sign:=-1.0
elseif chr=="."
dptr:=sptr
elseif chr =>48 AND chr =< 57
retv:=retv*10+(chr-48)
elseif chr==" "
quit
byte[noparse][[/noparse]sptr]:=" "
sptr++
retv:=f.fdiv(f.ffloat(retv),tenf[noparse][[/noparse]sptr-dptr-1])
if sign <> 0
retv:=f.fmul(retv,sign)
PUB ParseFloat(sptr) :retv | dptr,chr,sign
sign:=0
dptr:=0
retv:=0
repeat
if byte[noparse][[/noparse]sptr] <>" "
quit
sptr++
repeat
chr:=byte[noparse][[/noparse]sptr]
if chr==0
quit
elseif chr=="-"
sign:=-1.0
elseif chr=="."
dptr:=sptr
elseif chr =>48 AND chr =< 57
retv:=retv*10+(chr-48)
elseif chr==" "
quit
byte[noparse][[/noparse]sptr]:=" "
sptr++
retv:=f.fdiv(f.ffloat(retv),tenf[noparse][[/noparse]sptr-dptr-1])
if sign <> 0
retv:=f.fmul(retv,sign)
Comments
sign:=0
dptr:=0
retv:=0
repeat
if byte[noparse][[/noparse]sptr] <>" "
quit
sptr++
repeat
chr:=byte[noparse][[/noparse]sptr]
if chr==0
quit
elseif chr=="-"
sign:=-1.0
elseif chr=="."
dptr:=sptr
elseif chr =>48 AND chr =< 57
retv:=retv*10+(chr-48)
elseif chr==" "
quit
byte[noparse][[/noparse]sptr]:=" "
sptr++
retv:=f.fdiv(f.ffloat(retv),tenf[noparse][[/noparse]sptr-dptr-1])
if sign <> 0
retv:=f.fmul(retv,sign)
PUB ParseFloat(sptr) :retv | dptr,chr,sign
sign:=0
dptr:=0
retv:=0
repeat
if byte[noparse][[/noparse]sptr] <>" "
quit
sptr++
repeat
chr:=byte[noparse][[/noparse]sptr]
if chr==0
quit
elseif chr=="-"
sign:=-1.0
elseif chr=="."
dptr:=sptr
elseif chr =>48 AND chr =< 57
retv:=retv*10+(chr-48)
elseif chr==" "
quit
byte[noparse][[/noparse]sptr]:=" "
sptr++
retv:=f.fdiv(f.ffloat(retv),tenf[noparse][[/noparse]sptr-dptr-1])
if sign <> 0
retv:=f.fmul(retv,sign)
etc. For instance, your routine will not parse the string "5000000000" correctly. Also, what
are the requirements on accuracy?
Writing an acceptable string-to-float (and even float-to-string) is a very interesting, challenging,
and fun task, but it is the details that will get you.
I saw the error you pointed out this morning, here is the latest:
With floating point, unless you're talking about integer values with fewer significant digits than the maximum precision of the floating point, you will not get "100% accuracy". That's just inherent to floating point. You only get about 23-24 bits of accuracy which is about 7 decimal digits.
floating point value for a given input).
But to make it reasonably easy perhaps an error of +/- 0.6ulp would be sufficiently
precise (i.e., you don't require +/- 0.5ulp, but are willing to give up a small fraction of a
ulp in order to simplify things).