[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
master d6d871a 2/2: Calc: simplify integer log2 and power of 2
From: |
Mattias Engdegård |
Subject: |
master d6d871a 2/2: Calc: simplify integer log2 and power of 2 |
Date: |
Mon, 7 Dec 2020 07:33:48 -0500 (EST) |
branch: master
commit d6d871a1a266421f1c47df57bde5b0da54dfe352
Author: Mattias Engdegård <mattiase@acm.org>
Commit: Mattias Engdegård <mattiase@acm.org>
Calc: simplify integer log2 and power of 2
We have bignums and fast primitives now; no caches are needed.
* lisp/calc/calc-bin.el (math-power-of-2-cache)
(math-big-power-of-2-cache): Remove.
(math-power-of-2, math-integer-log2): Simplify.
(calcFunc-ash): Don't call math-power-of-2 with negative argument.
---
lisp/calc/calc-bin.el | 48 ++++++++----------------------------------------
1 file changed, 8 insertions(+), 40 deletions(-)
diff --git a/lisp/calc/calc-bin.el b/lisp/calc/calc-bin.el
index e3b1013..6d93587 100644
--- a/lisp/calc/calc-bin.el
+++ b/lisp/calc/calc-bin.el
@@ -199,48 +199,16 @@
(message "Omitting leading zeros on integers"))))
-(defvar math-power-of-2-cache (list 1 2 4 8 16 32 64 128 256 512 1024))
-(defvar math-big-power-of-2-cache nil)
(defun math-power-of-2 (n) ; [I I] [Public]
- (if (and (natnump n) (<= n 100))
- (or (nth n math-power-of-2-cache)
- (let* ((i (length math-power-of-2-cache))
- (val (nth (1- i) math-power-of-2-cache)))
- (while (<= i n)
- (setq val (math-mul val 2)
- math-power-of-2-cache (nconc math-power-of-2-cache
- (list val))
- i (1+ i)))
- val))
- (let ((found (assq n math-big-power-of-2-cache)))
- (if found
- (cdr found)
- (let ((po2 (math-ipow 2 n)))
- (setq math-big-power-of-2-cache
- (cons (cons n po2) math-big-power-of-2-cache))
- po2)))))
+ (if (natnump n)
+ (ash 1 n)
+ (error "argument must be a natural number")))
(defun math-integer-log2 (n) ; [I I] [Public]
- (let ((i 0)
- (p math-power-of-2-cache)
- val)
- (while (and p (< (setq val (car p)) n))
- (setq p (cdr p)
- i (1+ i)))
- (if p
- (and (equal val n)
- i)
- (while (<
- (prog1
- (setq val (math-mul val 2))
- (setq math-power-of-2-cache (nconc math-power-of-2-cache
- (list val))))
- n)
- (setq i (1+ i)))
- (and (equal val n)
- i))))
-
-
+ (and (natnump n)
+ (not (zerop n))
+ (zerop (logand n (1- n)))
+ (logb n)))
;;; Bitwise operations.
@@ -404,7 +372,7 @@
(math-clip (calcFunc-ash a n (- w)) w)
(if (Math-integer-negp a)
(setq a (math-clip a w)))
- (let ((two-to-sizem1 (math-power-of-2 (1- w)))
+ (let ((two-to-sizem1 (and (not (zerop w)) (math-power-of-2 (1- w))))
(sh (calcFunc-lsh a n w)))
(cond ((or (zerop w)
(zerop (logand a two-to-sizem1)))