Guest User

An implementation of the ROUND() function in Forth

a guest
Oct 18th, 2026
23
0
336 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | Software | 0 0
  1. \ An implementation of the ROUND() function in Forth
  2. \
  3. \ N.B. not rigorously tested
  4. \
  5. \ A corresponding TRUNC() function should be possible
  6. \ by replacing FROUND with FTRUNC.
  7.  
  8. \ return x87 status bits C0 C1 C2 C3
  9. code xam ( r -- x )
  10. fsp ) di mov qword 0 [di] fld fxam ax fstsw
  11. st(0) fstp $47 # ah and bx bx sub ah bl mov
  12. 1 floats # fsp ) add bx push next
  13. end-code
  14.  
  15. \ return string and true if NAN/INF, else false
  16. : FBAD? ( F: r -- r ) ( -- a u -1 | 0 )
  17. fdup xam cond
  18. 1 of s" +NAN" else 3 of s" -NAN" else
  19. 5 of s" +INF" else 7 of s" -INF" else
  20. drop 0 exit
  21. cont -1 ;
  22.  
  23. 308 constant pmax
  24.  
  25. 1 0 d>f fconstant f1.
  26. 10 0 d>f fconstant f10.
  27.  
  28. \ raise r to the power n
  29. : F^N ( r n -- r^n )
  30. >r f1. fswap r> 0 of fdrop end
  31. dup >r abs begin dup 0> while
  32. dup >r 1 and if
  33. ftuck f* fswap
  34. then fdup f* r> 2/
  35. repeat drop fdrop
  36. r> 0< if f1. fswap f/ then ;
  37.  
  38. \ scale r1 left/right by n digits, giving r2
  39. : SCALE ( r1 n -- r2 )
  40. dup pmax > if pmax - >r f10. pmax f^n f*
  41. else >r then f10. r> f^n f* ;
  42.  
  43. \ round r1 to n decimal places, giving r2
  44. : ROUND ( r1 n -- r2 )
  45. >r fbad? if 2drop rdrop end
  46. r@ scale fround r> negate scale ;
  47.  
  48. \ testing
  49. :noname cr begin refill while source 2dup type space
  50. evaluate cr repeat ; execute
  51.  
  52. 876.543e 3 round f. 876.543
  53. 876.543e 2 round f. 876.54
  54. 876.543e 1 round f. 876.5
  55. 876.543e 0 round f. 877.
  56. 876.543e -1 round f. 880.
  57. 876.543e -2 round f. 900.
  58. 876.543e -3 round f. 1000.
  59.  
  60. 456.789e 3 round f. 456.789
  61. 456.789e 2 round f. 456.79
  62. 456.789e 1 round f. 456.8
  63. 456.789e 0 round f. 457.
  64. 456.789e -1 round f. 460.
  65. 456.789e -2 round f. 500.
  66. 456.789e -3 round f. 0.
  67.  
  68. +nan 3 round f. +NAN
  69. -inf -3 round f. -INF
  70.  
Advertisement
Add Comment
Please, Sign In to add comment