help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: percent-change


From: Ruijie Yu
Subject: Re: percent-change
Date: Sat, 13 May 2023 21:37:12 +0800
User-agent: mu4e 1.11.3; emacs 30.0.50

Emanuel Berg <incal@dataswamp.org> writes:

> Take a look at this, see examples for intended bahvior.
> This was more difficult than I imagined, maybe there is some
> simpler way to do it?
>
> Otherwise it just shows once again that computing something
> and writing a program to compute it are not the same ...
>
> ;;; -*- lexical-binding: t -*-
> ;;
> ;; this file:
> ;;   https://dataswamp.org/~incal/emacs-init/math.el
>
> (defun percent-change (from to)
>   (let ((dist (abs (- to from))))
>     (if (zerop dist)
>         0
>       (let ((change (abs (/ dist from 0.01))))
>         (if (< from to)
>             change
>           (* -1 change) )))))

This is my version.  All test cases seem to pass.

```emacs-lisp
(defun cfg-percent-change (from to)
  (cond
   ((< from 0) (- (cfg-percent-change (- from) (- to))))
   ((= from to) 0)
   ((/ (- to from) from 0.01))))
```

I think your version had an unnecessary double-abs, and tightening up
the logic resulted in my version.

And yes, computation is much different from coming up all the edge
casese for writing a program that does the computation for you. :)

> ;; (percent-change   1  2) ;  100
> ;; (percent-change   1  1) ;    0
> ;; (percent-change   1  0) ; -100
> ;; (percent-change   1 -1) ; -200
>
> ;; (percent-change   0  1) ;  1.0e+INF
> ;; (percent-change   0  0) ;  0
> ;; (percent-change   0 -1) ; -1.0e+INF
>
> ;; (percent-change  -1  1) ;  200
> ;; (percent-change  -1  0) ;  100
> ;; (percent-change  -1 -1) ;    0
> ;; (percent-change  -1 -2) ; -100


-- 
Best,


RY



reply via email to

[Prev in Thread] Current Thread [Next in Thread]