Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- \ An implementation of the ROUND() function in Forth
- \
- \ N.B. not rigorously tested
- \
- \ A corresponding TRUNC() function should be possible
- \ by replacing FROUND with FTRUNC.
- \ return x87 status bits C0 C1 C2 C3
- code xam ( r -- x )
- fsp ) di mov qword 0 [di] fld fxam ax fstsw
- st(0) fstp $47 # ah and bx bx sub ah bl mov
- 1 floats # fsp ) add bx push next
- end-code
- \ return string and true if NAN/INF, else false
- : FBAD? ( F: r -- r ) ( -- a u -1 | 0 )
- fdup xam cond
- 1 of s" +NAN" else 3 of s" -NAN" else
- 5 of s" +INF" else 7 of s" -INF" else
- drop 0 exit
- cont -1 ;
- 308 constant pmax
- 1 0 d>f fconstant f1.
- 10 0 d>f fconstant f10.
- \ raise r to the power n
- : F^N ( r n -- r^n )
- >r f1. fswap r> 0 of fdrop end
- dup >r abs begin dup 0> while
- dup >r 1 and if
- ftuck f* fswap
- then fdup f* r> 2/
- repeat drop fdrop
- r> 0< if f1. fswap f/ then ;
- \ scale r1 left/right by n digits, giving r2
- : SCALE ( r1 n -- r2 )
- dup pmax > if pmax - >r f10. pmax f^n f*
- else >r then f10. r> f^n f* ;
- \ round r1 to n decimal places, giving r2
- : ROUND ( r1 n -- r2 )
- >r fbad? if 2drop rdrop end
- r@ scale fround r> negate scale ;
- \ testing
- :noname cr begin refill while source 2dup type space
- evaluate cr repeat ; execute
- 876.543e 3 round f. 876.543
- 876.543e 2 round f. 876.54
- 876.543e 1 round f. 876.5
- 876.543e 0 round f. 877.
- 876.543e -1 round f. 880.
- 876.543e -2 round f. 900.
- 876.543e -3 round f. 1000.
- 456.789e 3 round f. 456.789
- 456.789e 2 round f. 456.79
- 456.789e 1 round f. 456.8
- 456.789e 0 round f. 457.
- 456.789e -1 round f. 460.
- 456.789e -2 round f. 500.
- 456.789e -3 round f. 0.
- +nan 3 round f. +NAN
- -inf -3 round f. -INF
Advertisement
Add Comment
Please, Sign In to add comment