User:Eriksiers/Alternate CLISP exponentiation: Difference between revisions
Content added Content deleted
m (added footnote to Ahungry's example) |
m (updated lang tag) |
||
Line 1: | Line 1: | ||
This is a better example of exponent (it doesn't solve for negatives however so I will leave in tact the other example): |
This is a better example of exponent (it doesn't solve for negatives however so I will leave in tact the other example): |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun ^ (a b) |
(defun ^ (a b) |
||
(let ((r 1)) |
(let ((r 1)) |
||
(dotimes (x b r) |
(dotimes (x b r) |
||
(setf r (* r a))))) |
(setf r (* r a))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
<small>(The above example is by [[User:Ahungry|Ahungry]].)</small> |
<small>(The above example is by [[User:Ahungry|Ahungry]].)</small> |
||
Line 16: | Line 16: | ||
Later, I might update this to handle [[Nth root|b as a float]]. |
Later, I might update this to handle [[Nth root|b as a float]]. |
||
< |
<syntaxhighlight lang="lisp">; calculates a to the bth power (a^b) |
||
; b must be an integer |
; b must be an integer |
||
; a can be integer or floating-point |
; a can be integer or floating-point |
||
Line 39: | Line 39: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
Sample outputs: |
Sample outputs: |
Latest revision as of 04:57, 1 September 2022
This is a better example of exponent (it doesn't solve for negatives however so I will leave in tact the other example):
(defun ^ (a b)
(let ((r 1))
(dotimes (x b r)
(setf r (* r a)))))
(The above example is by Ahungry.)
I wrote this while reading the first few chapters of Practical Common Lisp. (I'm about halfway through chapter 4 right now.) It seems to work -- at least for me, using CLISP -- and I think it might be a better version than the "real" solution provided at Exponentiation operator#Common Lisp, but I'm still way too green to know for sure. (This version can handle negative values of b, whereas that version can't -- I think.)
FWIW, I wrote this before looking at the Exponentiation operator page. Yay me.
Later, I might update this to handle b as a float.
; calculates a to the bth power (a^b)
; b must be an integer
; a can be integer or floating-point
; either or both can be negative
; limits determined by lisp, I suppose -- arbitrary? none? I don't know
(defun ^ (a b)
(if
(> b 0)
(* a
(^ a
(- b 1)
)
)
(if
(< b 0)
(/ 1
(^ a
(- 0 b)
)
)
(if (= b 0) 1)
)
)
)
Sample outputs:
CL-USER> (^ 1.1 2) 1.21 CL-USER> (^ -1 2) 1 CL-USER> (^ -1 3) -1 CL-USER> (^ -1.1 -1) -0.9090909 CL-USER> (^ 2 300) 2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397376 CL-USER> (^ 1 .5) ; Evaluation aborted on NIL.