float.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. ;; Copyright (C) 1986 Free Software Foundation, Inc.
  2. ;; Author Bill Rosenblatt
  3. ;; This file is part of GNU Emacs.
  4. ;; GNU Emacs is distributed in the hope that it will be useful,
  5. ;; but WITHOUT ANY WARRANTY. No author or distributor
  6. ;; accepts responsibility to anyone for the consequences of using it
  7. ;; or for whether it serves any particular purpose or works at all,
  8. ;; unless he says so in writing. Refer to the GNU Emacs General Public
  9. ;; License for full details.
  10. ;; Everyone is granted permission to copy, modify and redistribute
  11. ;; GNU Emacs, but only under the conditions described in the
  12. ;; GNU Emacs General Public License. A copy of this license is
  13. ;; supposed to have been given to you along with GNU Emacs so you
  14. ;; can know your rights and responsibilities. It should be in a
  15. ;; file named COPYING. Among other things, the copyright notice
  16. ;; and this notice must be preserved on all copies.
  17. ;; Floating point arithmetic package.
  18. ;;
  19. ;; Floating point numbers are represented by dot-pairs (mant . exp)
  20. ;; where mant is the 24-bit signed integral mantissa and exp is the
  21. ;; base 2 exponent.
  22. ;;
  23. ;; Emacs LISP supports a 24-bit signed integer data type, which has a
  24. ;; range of -(2**23) to +(2**23)-1, or -8388608 to 8388607 decimal.
  25. ;; This gives six significant decimal digit accuracy. Exponents can
  26. ;; be anything in the range -(2**23) to +(2**23)-1.
  27. ;;
  28. ;; User interface:
  29. ;; function f converts from integer to floating point
  30. ;; function string-to-float converts from string to floating point
  31. ;; function fint converts a floating point to integer (with truncation)
  32. ;; function float-to-string converts from floating point to string
  33. ;;
  34. ;; Caveats:
  35. ;; - Exponents outside of the range of +/-100 or so will cause certain
  36. ;; functions (especially conversion routines) to take forever.
  37. ;; - Very little checking is done for fixed point overflow/underflow.
  38. ;; - No checking is done for over/underflow of the exponent
  39. ;; (hardly necessary when exponent can be 2**23).
  40. ;;
  41. ;;
  42. ;; Bill Rosenblatt
  43. ;; June 20, 1986
  44. ;;
  45. ;; fundamental implementation constants
  46. (defconst exp-base 2
  47. "Base of exponent in this floating point representation.")
  48. (defconst mantissa-bits 24
  49. "Number of significant bits in this floating point representation.")
  50. (defconst decimal-digits 6
  51. "Number of decimal digits expected to be accurate.")
  52. (defconst expt-digits 2
  53. "Maximum permitted digits in a scientific notation exponent.")
  54. ;; other constants
  55. (defconst maxbit (1- mantissa-bits)
  56. "Number of highest bit")
  57. (defconst mantissa-maxval (1- (ash 1 maxbit))
  58. "Maximum permissable value of mantissa")
  59. (defconst mantissa-minval (ash 1 maxbit)
  60. "Minimum permissable value of mantissa")
  61. (defconst floating-point-regexp
  62. "^[ \t]*\\(-?\\)\\([0-9]*\\)\
  63. \\(\\.\\([0-9]*\\)\\|\\)\
  64. \\(\\(\\([Ee]\\)\\(-?\\)\\([0-9][0-9]*\\)\\)\\|\\)[ \t]*$"
  65. "Regular expression to match floating point numbers. Extract matches:
  66. 1 - minus sign
  67. 2 - integer part
  68. 4 - fractional part
  69. 8 - minus sign for power of ten
  70. 9 - power of ten
  71. ")
  72. (defconst high-bit-mask (ash 1 maxbit)
  73. "Masks all bits except the high-order (sign) bit.")
  74. (defconst second-bit-mask (ash 1 (1- maxbit))
  75. "Masks all bits except the highest-order magnitude bit")
  76. ;; various useful floating point constants
  77. (setq _f0 '(0 . 1))
  78. (setq _f1/2 '(4194304 . -23))
  79. (setq _f1 '(4194304 . -22))
  80. (setq _f10 '(5242880 . -19))
  81. ;; support for decimal conversion routines
  82. (setq powers-of-10 (make-vector (1+ decimal-digits) _f1))
  83. (aset powers-of-10 1 _f10)
  84. (aset powers-of-10 2 '(6553600 . -16))
  85. (aset powers-of-10 3 '(8192000 . -13))
  86. (aset powers-of-10 4 '(5120000 . -9))
  87. (aset powers-of-10 5 '(6400000 . -6))
  88. (aset powers-of-10 6 '(8000000 . -3))
  89. (setq all-decimal-digs-minval (aref powers-of-10 (1- decimal-digits))
  90. highest-power-of-10 (aref powers-of-10 decimal-digits))
  91. (defun fashl (fnum) ; floating-point arithmetic shift left
  92. (cons (ash (car fnum) 1) (1- (cdr fnum))))
  93. (defun fashr (fnum) ; floating point arithmetic shift right
  94. (cons (ash (car fnum) -1) (1+ (cdr fnum))))
  95. (defun normalize (fnum)
  96. (if (> (car fnum) 0) ; make sure next-to-highest bit is set
  97. (while (zerop (logand (car fnum) second-bit-mask))
  98. (setq fnum (fashl fnum)))
  99. (if (< (car fnum) 0) ; make sure highest bit is set
  100. (while (zerop (logand (car fnum) high-bit-mask))
  101. (setq fnum (fashl fnum)))
  102. (setq fnum _f0))) ; "standard 0"
  103. fnum)
  104. (defun abs (n) ; integer absolute value
  105. (if (natnump n) n (- n)))
  106. (defun fabs (fnum) ; re-normalize after taking abs value
  107. (normalize (cons (abs (car fnum)) (cdr fnum))))
  108. (defun xor (a b) ; logical exclusive or
  109. (and (or a b) (not (and a b))))
  110. (defun same-sign (a b) ; two f-p numbers have same sign?
  111. (not (xor (natnump (car a)) (natnump (car b)))))
  112. (defun extract-match (str i) ; used after string-match
  113. (condition-case ()
  114. (substring str (match-beginning i) (match-end i))
  115. (error "")))
  116. ;; support for the multiplication function
  117. (setq halfword-bits (/ mantissa-bits 2) ; bits in a halfword
  118. masklo (1- (ash 1 halfword-bits)) ; isolate the lower halfword
  119. maskhi (lognot masklo) ; isolate the upper halfword
  120. round-limit (ash 1 (/ halfword-bits 2)))
  121. (defun hihalf (n) ; return high halfword, shifted down
  122. (ash (logand n maskhi) (- halfword-bits)))
  123. (defun lohalf (n) ; return low halfword
  124. (logand n masklo))
  125. ;; Visible functions
  126. ;; Arithmetic functions
  127. (defun f+ (a1 a2)
  128. "Returns the sum of two floating point numbers."
  129. (let ((f1 (fmax a1 a2))
  130. (f2 (fmin a1 a2)))
  131. (if (same-sign a1 a2)
  132. (setq f1 (fashr f1) ; shift right to avoid overflow
  133. f2 (fashr f2)))
  134. (normalize
  135. (cons (+ (car f1) (ash (car f2) (- (cdr f2) (cdr f1))))
  136. (cdr f1)))))
  137. (defun f- (a1 &optional a2) ; unary or binary minus
  138. "Returns the difference of two floating point numbers."
  139. (if a2
  140. (f+ a1 (f- a2))
  141. (normalize (cons (- (car a1)) (cdr a1)))))
  142. (defun f* (a1 a2) ; multiply in halfword chunks
  143. "Returns the product of two floating point numbers."
  144. (let* ((i1 (car (fabs a1)))
  145. (i2 (car (fabs a2)))
  146. (sign (not (same-sign a1 a2)))
  147. (prodlo (+ (hihalf (* (lohalf i1) (lohalf i2)))
  148. (lohalf (* (hihalf i1) (lohalf i2)))
  149. (lohalf (* (lohalf i1) (hihalf i2)))))
  150. (prodhi (+ (* (hihalf i1) (hihalf i2))
  151. (hihalf (* (hihalf i1) (lohalf i2)))
  152. (hihalf (* (lohalf i1) (hihalf i2)))
  153. (hihalf prodlo))))
  154. (if (> (lohalf prodlo) round-limit)
  155. (setq prodhi (1+ prodhi))) ; round off truncated bits
  156. (normalize
  157. (cons (if sign (- prodhi) prodhi)
  158. (+ (cdr (fabs a1)) (cdr (fabs a2)) mantissa-bits)))))
  159. (defun f/ (a1 a2) ; SLOW subtract-and-shift algorithm
  160. "Returns the quotient of two floating point numbers."
  161. (if (zerop (car a2)) ; if divide by 0
  162. (signal 'arith-error (list "attempt to divide by zero" a1 a2))
  163. (let ((bits (1- maxbit))
  164. (quotient 0)
  165. (dividend (car (fabs a1)))
  166. (divisor (car (fabs a2)))
  167. (sign (not (same-sign a1 a2))))
  168. (while (natnump bits)
  169. (if (< (- dividend divisor) 0)
  170. (setq quotient (ash quotient 1))
  171. (setq quotient (1+ (ash quotient 1))
  172. dividend (- dividend divisor)))
  173. (setq dividend (ash dividend 1)
  174. bits (1- bits)))
  175. (normalize
  176. (cons (if sign (- quotient) quotient)
  177. (- (cdr (fabs a1)) (cdr (fabs a2)) (1- maxbit)))))))
  178. (defun f% (a1 a2)
  179. "Returns the remainder of first floating point number divided by second."
  180. (f- a1 (f* (ftrunc (f/ a1 a2)) a2)))
  181. ;; Comparison functions
  182. (defun f= (a1 a2)
  183. "Returns t if two floating point numbers are equal, nil otherwise."
  184. (equal a1 a2))
  185. (defun f> (a1 a2)
  186. "Returns t if first floating point number is greater than second,
  187. nil otherwise."
  188. (cond ((and (natnump (car a1)) (< (car a2) 0))
  189. t) ; a1 nonnegative, a2 negative
  190. ((and (> (car a1) 0) (<= (car a2) 0))
  191. t) ; a1 positive, a2 nonpositive
  192. ((and (<= (car a1) 0) (natnump (car a2)))
  193. nil) ; a1 nonpos, a2 nonneg
  194. ((/= (cdr a1) (cdr a2)) ; same signs. exponents differ
  195. (> (cdr a1) (cdr a2))) ; compare the mantissas.
  196. (t
  197. (> (car a1) (car a2))))) ; same exponents.
  198. (defun f>= (a1 a2)
  199. "Returns t if first floating point number is greater than or equal to
  200. second, nil otherwise."
  201. (or (f> a1 a2) (f= a1 a2)))
  202. (defun f< (a1 a2)
  203. "Returns t if first floating point number is less than second,
  204. nil otherwise."
  205. (not (f>= a1 a2)))
  206. (defun f<= (a1 a2)
  207. "Returns t if first floating point number is less than or equal to
  208. second, nil otherwise."
  209. (not (f> a1 a2)))
  210. (defun f/= (a1 a2)
  211. "Returns t if first floating point number is not equal to second,
  212. nil otherwise."
  213. (not (f= a1 a2)))
  214. (defun fmin (a1 a2)
  215. "Returns the minimum of two floating point numbers."
  216. (if (f< a1 a2) a1 a2))
  217. (defun fmax (a1 a2)
  218. "Returns the maximum of two floating point numbers."
  219. (if (f> a1 a2) a1 a2))
  220. (defun fzerop (fnum)
  221. "Returns t if the floating point number is zero, nil otherwise."
  222. (= (car fnum) 0))
  223. (defun floatp (fnum)
  224. "Returns t if the arg is a floating point number, nil otherwise."
  225. (and (consp fnum) (integerp (car fnum)) (integerp (cdr fnum))))
  226. ;; Conversion routines
  227. (defun f (int)
  228. "Convert the integer argument to floating point, like a C cast operator."
  229. (normalize (cons int '0)))
  230. (defun int-to-hex-string (int)
  231. "Convert the integer argument to a C-style hexadecimal string."
  232. (let ((shiftval -20)
  233. (str "0x")
  234. (hex-chars "0123456789ABCDEF"))
  235. (while (<= shiftval 0)
  236. (setq str (concat str (char-to-string
  237. (aref hex-chars
  238. (logand (lsh int shiftval) 15))))
  239. shiftval (+ shiftval 4)))
  240. str))
  241. (defun ftrunc (fnum) ; truncate fractional part
  242. "Truncate the fractional part of a floating point number."
  243. (cond ((natnump (cdr fnum)) ; it's all integer, return number as is
  244. fnum)
  245. ((<= (cdr fnum) (- maxbit)) ; it's all fractional, return 0
  246. '(0 . 1))
  247. (t ; otherwise mask out fractional bits
  248. (let ((mant (car fnum)) (exp (cdr fnum)))
  249. (normalize
  250. (cons (if (natnump mant) ; if negative, use absolute value
  251. (ash (ash mant exp) (- exp))
  252. (- (ash (ash (- mant) exp) (- exp))))
  253. exp))))))
  254. (defun fint (fnum) ; truncate and convert to integer
  255. "Convert the floating point number to integer, with truncation,
  256. like a C cast operator."
  257. (let* ((tf (ftrunc fnum)) (tint (car tf)) (texp (cdr tf)))
  258. (cond ((>= texp mantissa-bits) ; too high, return "maxint"
  259. mantissa-maxval)
  260. ((<= texp (- mantissa-bits)) ; too low, return "minint"
  261. mantissa-minval)
  262. (t ; in range
  263. (ash tint texp))))) ; shift so that exponent is 0
  264. (defun float-to-string (fnum &optional sci)
  265. "Convert the floating point number to a decimal string.
  266. Optional second argument non-nil means use scientific notation."
  267. (let* ((value (fabs fnum)) (sign (< (car fnum) 0))
  268. (power 0) (result 0) (str "")
  269. (temp 0) (pow10 _f1))
  270. (if (f= fnum _f0)
  271. "0"
  272. (if (f>= value _f1) ; find largest power of 10 <= value
  273. (progn ; value >= 1, power is positive
  274. (while (f<= (setq temp (f* pow10 highest-power-of-10)) value)
  275. (setq pow10 temp
  276. power (+ power decimal-digits)))
  277. (while (f<= (setq temp (f* pow10 _f10)) value)
  278. (setq pow10 temp
  279. power (1+ power))))
  280. (progn ; value < 1, power is negative
  281. (while (f> (setq temp (f/ pow10 highest-power-of-10)) value)
  282. (setq pow10 temp
  283. power (- power decimal-digits)))
  284. (while (f> pow10 value)
  285. (setq pow10 (f/ pow10 _f10)
  286. power (1- power)))))
  287. ; get value in range 100000 to 999999
  288. (setq value (f* (f/ value pow10) all-decimal-digs-minval)
  289. result (ftrunc value))
  290. (if (f> (f- value result) _f1/2) ; round up if remainder > 0.5
  291. (setq str (int-to-string (1+ (fint result))))
  292. (setq str (int-to-string (fint result))))
  293. (if sci ; scientific notation
  294. (setq str (concat (substring str 0 1) "." (substring str 1)
  295. "E" (int-to-string power)))
  296. ; regular decimal string
  297. (cond ((>= power (1- decimal-digits))
  298. ; large power, append zeroes
  299. (let ((zeroes (- power decimal-digits)))
  300. (while (natnump zeroes)
  301. (setq str (concat str "0")
  302. zeroes (1- zeroes)))))
  303. ; negative power, prepend decimal
  304. ((< power 0) ; point and zeroes
  305. (let ((zeroes (- (- power) 2)))
  306. (while (natnump zeroes)
  307. (setq str (concat "0" str)
  308. zeroes (1- zeroes)))
  309. (setq str (concat "0." str))))
  310. (t ; in range, insert decimal point
  311. (setq str (concat
  312. (substring str 0 (1+ power))
  313. "."
  314. (substring str (1+ power)))))))
  315. (if sign ; if negative, prepend minus sign
  316. (concat "-" str)
  317. str))))
  318. ;; string to float conversion.
  319. ;; accepts scientific notation, but ignores anything after the first two
  320. ;; digits of the exponent.
  321. (defun string-to-float (str)
  322. "Convert the string to a floating point number.
  323. Accepts a decimal string in scientific notation,
  324. with exponent preceded by either E or e.
  325. Only the 6 most significant digits of the integer and fractional parts
  326. are used; only the first two digits of the exponent are used.
  327. Negative signs preceding both the decimal number and the exponent
  328. are recognized."
  329. (if (string-match floating-point-regexp str 0)
  330. (let (power)
  331. (f*
  332. ; calculate the mantissa
  333. (let* ((int-subst (extract-match str 2))
  334. (fract-subst (extract-match str 4))
  335. (digit-string (concat int-subst fract-subst))
  336. (mant-sign (equal (extract-match str 1) "-"))
  337. (leading-0s 0) (round-up nil))
  338. ; get rid of leading 0's
  339. (setq power (- (length int-subst) decimal-digits))
  340. (while (and (< leading-0s (length digit-string))
  341. (= (aref digit-string leading-0s) ?0))
  342. (setq leading-0s (1+ leading-0s)))
  343. (setq power (- power leading-0s)
  344. digit-string (substring digit-string leading-0s))
  345. ; if more than 6 digits, round off
  346. (if (> (length digit-string) decimal-digits)
  347. (setq round-up (>= (aref digit-string decimal-digits) ?5)
  348. digit-string (substring digit-string 0 decimal-digits))
  349. (setq power (+ power (- decimal-digits (length digit-string)))))
  350. ; round up and add minus sign, if necessary
  351. (f (* (+ (string-to-int digit-string)
  352. (if round-up 1 0))
  353. (if mant-sign -1 1))))
  354. ; calculate the exponent (power of ten)
  355. (let* ((expt-subst (extract-match str 9))
  356. (expt-sign (equal (extract-match str 8) "-"))
  357. (expt 0) (chunks 0) (tens 0) (exponent _f1)
  358. (func 'f*))
  359. (setq expt (+ (* (string-to-int
  360. (substring expt-subst 0
  361. (min expt-digits (length expt-subst))))
  362. (if expt-sign -1 1))
  363. power))
  364. (if (< expt 0) ; if power of 10 negative
  365. (setq expt (- expt) ; take abs val of exponent
  366. func 'f/)) ; and set up to divide, not multiply
  367. (setq chunks (/ expt decimal-digits)
  368. tens (% expt decimal-digits))
  369. ; divide or multiply by "chunks" of 10**6
  370. (while (> chunks 0)
  371. (setq exponent (funcall func exponent highest-power-of-10)
  372. chunks (1- chunks)))
  373. ; divide or multiply by remaining power of ten
  374. (funcall func exponent (aref powers-of-10 tens)))))
  375. _f0)) ; if invalid, return 0