Merge branch 'master' into comment-cache
[emacs.git] / lisp / calc / calc-units.el
blob0e3715eb4cf20cd4472241d88ce8fb96086b7c23
1 ;;; calc-units.el --- unit conversion functions for Calc
3 ;; Copyright (C) 1990-1993, 2001-2017 Free Software Foundation, Inc.
5 ;; Author: David Gillespie <daveg@synaptics.com>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;;; Commentary:
24 ;;; Code:
26 ;; This file is autoloaded from calc-ext.el.
28 (require 'calc-ext)
29 (require 'calc-macs)
30 (eval-when-compile
31 (require 'calc-alg))
33 ;;; Units operations.
35 ;;; Units table last updated 9-Jan-91 by Ulrich Mueller (ulm@vsnhd1.cern.ch)
36 ;;; with some additions by Przemek Klosowski (przemek@rrdstrad.nist.gov)
37 ;;; Updated April 2002 by Jochen Küpper
39 ;;; Updated August 2007, using
40 ;;; CODATA (http://physics.nist.gov/cuu/Constants/index.html)
41 ;;; NIST (http://physics.nist.gov/Pubs/SP811/appenB9.html)
42 ;;; ESUWM (Encyclopaedia of Scientific Units, Weights and
43 ;;; Measures, by François Cardarelli)
44 ;;; All conversions are exact unless otherwise noted.
46 ;; CODATA values updated February 2016, using 2014 adjustment
47 ;; http://arxiv.org/pdf/1507.07956.pdf
49 (defvar math-standard-units
50 '( ;; Length
51 ( m nil "*Meter" )
52 ( in "254*10^(-2) cm" "Inch" nil
53 "2.54 cm")
54 ( ft "12 in" "Foot")
55 ( yd "3 ft" "Yard" )
56 ( mi "5280 ft" "Mile" )
57 ( au "149597870691. m" "Astronomical Unit" nil
58 "149597870691 m (*)")
59 ;; (approx) NASA JPL (http://neo.jpl.nasa.gov/glossary/au.html)
60 ( lyr "c yr" "Light Year" )
61 ( pc "3.0856775854*10^16 m" "Parsec (**)" nil
62 "3.0856775854 10^16 m (*)") ;; (approx) ESUWM
63 ( nmi "1852 m" "Nautical Mile" )
64 ( fath "6 ft" "Fathom" )
65 ( fur "660 ft" "Furlong")
66 ( mu "1 um" "Micron" )
67 ( mil "(1/1000) in" "Mil" )
68 ( point "(1/72) in" "Point (PostScript convention)" )
69 ( Ang "10^(-10) m" "Angstrom" )
70 ( mfi "mi+ft+in" "Miles + feet + inches" )
71 ;; TeX lengths
72 ( texpt "(100/7227) in" "Point (TeX convention) (**)" )
73 ( texpc "12 texpt" "Pica (TeX convention) (**)" )
74 ( texbp "point" "Big point (TeX convention) (**)" )
75 ( texdd "(1238/1157) texpt" "Didot point (TeX convention) (**)" )
76 ( texcc "12 texdd" "Cicero (TeX convention) (**)" )
77 ( texsp "(1/65536) texpt" "Scaled TeX point (TeX convention) (**)" )
79 ;; Area
80 ( hect "10000 m^2" "*Hectare" )
81 ( a "100 m^2" "Are")
82 ( acre "(1/640) mi^2" "Acre" )
83 ( b "10^(-28) m^2" "Barn" )
85 ;; Volume
86 ( L "10^(-3) m^3" "*Liter" )
87 ( l "L" "Liter" )
88 ( gal "4 qt" "US Gallon" )
89 ( qt "2 pt" "Quart" )
90 ( pt "2 cup" "Pint (**)" )
91 ( cup "8 ozfl" "Cup" )
92 ( ozfl "2 tbsp" "Fluid Ounce" )
93 ( floz "2 tbsp" "Fluid Ounce" )
94 ( tbsp "3 tsp" "Tablespoon" )
95 ;; ESUWM defines a US gallon as 231 in^3.
96 ;; That gives the following exact value for tsp.
97 ( tsp "492892159375*10^(-11) ml" "Teaspoon" nil
98 "4.92892159375 ml")
99 ( vol "tsp+tbsp+ozfl+cup+pt+qt+gal" "Gallons + ... + teaspoons" nil
100 "tsp+tbsp+ozfl+cup+pt+qt+gal")
101 ( galC "galUK" "Canadian Gallon" )
102 ( galUK "454609*10^(-5) L" "UK Gallon" nil
103 "4.54609 L") ;; NIST
105 ;; Time
106 ( s nil "*Second" )
107 ( sec "s" "Second" )
108 ( min "60 s" "Minute" )
109 ( hr "60 min" "Hour" )
110 ( day "24 hr" "Day" )
111 ( wk "7 day" "Week" )
112 ( hms "wk+day+hr+min+s" "Hours, minutes, seconds" )
113 ( yr "36525*10^(-2) day" "Year (Julian)" nil
114 "365.25 day")
115 ( Hz "1/s" "Hertz" )
117 ;; Speed
118 ( mph "mi/hr" "*Miles per hour" )
119 ( kph "km/hr" "Kilometers per hour" )
120 ( knot "nmi/hr" "Knot" )
121 ( c "299792458 m/s" "Speed of light" ) ;;; CODATA
123 ;; Acceleration
124 ( ga "980665*10^(-5) m/s^2" "*\"g\" acceleration" nil
125 "9.80665 m / s^2") ;; CODATA
127 ;; Mass
128 ( g nil "*Gram" )
129 ( lb "16 oz" "Pound (mass)" )
130 ( oz "28349523125*10^(-9) g" "Ounce (mass)" nil
131 "28.349523125 g") ;; ESUWM
132 ( ton "2000 lb" "Ton" )
133 ( tpo "ton+lb+oz" "Tons + pounds + ounces (mass)" )
134 ( t "1000 kg" "Metric ton" )
135 ( tonUK "10160469088*10^(-7) kg" "UK ton" nil
136 "1016.0469088 kg") ;; ESUWM
137 ( lbt "12 ozt" "Troy pound" )
138 ( ozt "311034768*10^(-7) g" "Troy ounce" nil
139 "31.10347680 g") ;; ESUWM, 1/12 exact value for lbt
140 ( ct "(2/10) g" "Carat" nil
141 "0.2 g") ;; ESUWM
142 ( u "1.660539040*10^(-27) kg" "Unified atomic mass" nil
143 "1.660539040 10^-27 kg (*)");;(approx) CODATA
145 ;; Force
146 ( N "m kg/s^2" "*Newton" )
147 ( dyn "10^(-5) N" "Dyne" )
148 ( gf "ga g" "Gram (force)" )
149 ( lbf "ga lb" "Pound (force)" )
150 ( kip "1000 lbf" "Kilopound (force)" )
151 ( pdl "138254954376*10^(-12) N" "Poundal" nil
152 "0.138254954376 N") ;; ESUWM
154 ;; Energy
155 ( J "N m" "*Joule" )
156 ( erg "10^(-7) J" "Erg" )
157 ( cal "41868*10^(-4) J" "International Table Calorie" nil
158 "4.1868 J") ;; NIST
159 ( calth "4184*10^(-3) J" "Thermochemical Calorie" nil
160 "4.184 J") ;; NIST
161 ( Cal "1000 cal" "Large Calorie")
162 ( Btu "105505585262*10^(-8) J" "International Table Btu" nil
163 "1055.05585262 J") ;; ESUWM
164 ( eV "ech V" "Electron volt" )
165 ( ev "eV" "Electron volt" )
166 ( therm "105506000 J" "EEC therm" )
167 ( invcm "h c/cm" "Energy in inverse centimeters" )
168 ( Kayser "invcm" "Kayser (inverse centimeter energy)" )
169 ( men "100/invcm" "Inverse energy in meters" )
170 ( Hzen "h Hz" "Energy in Hertz")
171 ( Ken "k K" "Energy in Kelvins")
172 ( Wh "W hr" "Watt hour")
173 ( Ws "W s" "Watt second")
175 ;; Power
176 ( W "J/s" "*Watt" )
177 ( hp "550 ft lbf/s" "Horsepower") ;;ESUWM
178 ( hpm "75 m kgf/s" "Metric Horsepower") ;;ESUWM
180 ;; Temperature
181 ( K nil "*Degree Kelvin" K )
182 ( dK "K" "Degree Kelvin" K )
183 ( degK "K" "Degree Kelvin" K )
184 ( dC "K" "Degree Celsius" C )
185 ( degC "K" "Degree Celsius" C )
186 ( dF "(5/9) K" "Degree Fahrenheit" F )
187 ( degF "(5/9) K" "Degree Fahrenheit" F )
189 ;; Pressure
190 ( Pa "N/m^2" "*Pascal" )
191 ( bar "10^5 Pa" "Bar" )
192 ( atm "101325 Pa" "Standard atmosphere" ) ;; CODATA
193 ( Torr "(1/760) atm" "Torr")
194 ( mHg "1000 Torr" "Meter of mercury" )
195 ( inHg "254*10^(-1) mmHg" "Inch of mercury" nil
196 "25.4 mmHg")
197 ( inH2O "2.490889*10^2 Pa" "Inch of water" nil
198 "2.490889 10^2 Pa (*)") ;;(approx) NIST
199 ( psi "lbf/in^2" "Pounds per square inch" )
201 ;; Viscosity
202 ( P "(1/10) Pa s" "*Poise" )
203 ( St "10^(-4) m^2/s" "Stokes" )
205 ;; Electromagnetism
206 ( A nil "*Ampere" )
207 ( C "A s" "Coulomb" )
208 ( Fdy "ech Nav" "Faraday" )
209 ( e "ech" "Elementary charge" )
210 ( ech "1.6021766208*10^(-19) C" "Elementary charge" nil
211 "1.6021766208 10^-19 C (*)") ;;(approx) CODATA
212 ( V "W/A" "Volt" )
213 ( ohm "V/A" "Ohm" )
214 ( Ω "ohm" "Ohm" )
215 ( mho "A/V" "Mho" )
216 ( S "A/V" "Siemens" )
217 ( F "C/V" "Farad" )
218 ( H "Wb/A" "Henry" )
219 ( T "Wb/m^2" "Tesla" )
220 ( Gs "10^(-4) T" "Gauss" )
221 ( Wb "V s" "Weber" )
223 ;; Luminous intensity
224 ( cd nil "*Candela" )
225 ( sb "10000 cd/m^2" "Stilb" )
226 ( lm "cd sr" "Lumen" )
227 ( lx "lm/m^2" "Lux" )
228 ( ph "10000 lx" "Phot" )
229 ( fc "lm/ft^2" "Footcandle") ;; ESUWM
230 ( lam "10000 lm/m^2" "Lambert" )
231 ( flam "(1/pi) cd/ft^2" "Footlambert") ;; ESUWM
233 ;; Radioactivity
234 ( Bq "1/s" "*Becquerel" )
235 ( Ci "37*10^9 Bq" "Curie" ) ;; ESUWM
236 ( Gy "J/kg" "Gray" )
237 ( Sv "Gy" "Sievert" )
238 ( R "258*10^(-6) C/kg" "Roentgen" ) ;; NIST
239 ( rd "(1/100) Gy" "Rad" )
240 ( rem "rd" "Rem" )
242 ;; Amount of substance
243 ( mol nil "*Mole" )
245 ;; Plane angle
246 ( rad nil "*Radian" )
247 ( circ "2 pi rad" "Full circle" )
248 ( rev "circ" "Full revolution" )
249 ( deg "circ/360" "Degree" )
250 ( arcmin "deg/60" "Arc minute" )
251 ( arcsec "arcmin/60" "Arc second" )
252 ( grad "circ/400" "Grade" )
253 ( rpm "rev/min" "Revolutions per minute" )
255 ;; Solid angle
256 ( sr nil "*Steradian" )
258 ;; Other physical quantities
259 ;; The values are from CODATA, and are approximate.
260 ( h "6.626070040*10^(-34) J s" "*Planck's constant" nil
261 "6.626070040 10^-34 J s (*)")
262 ( hbar "h / (2 pi)" "Planck's constant" ) ;; Exact
263 ( mu0 "4 pi 10^(-7) H/m" "Permeability of vacuum") ;; Exact
264 ( μ0 "mu0" "Permeability of vacuum") ;; Exact
265 ( eps0 "1 / (mu0 c^2)" "Permittivity of vacuum" )
266 ( ε0 "eps0" "Permittivity of vacuum" )
267 ( G "6.67408*10^(-11) m^3/(kg s^2)" "Gravitational constant" nil
268 "6.67408 10^-11 m^3/(kg s^2) (*)")
269 ( Nav "6.022140857*10^(23) / mol" "Avogadro's constant" nil
270 "6.022140857 10^23 / mol (*)")
271 ( me "9.10938356*10^(-31) kg" "Electron rest mass" nil
272 "9.10938356 10^-31 kg (*)")
273 ( mp "1.672621898*10^(-27) kg" "Proton rest mass" nil
274 "1.672621898 10^-27 kg (*)")
275 ( mn "1.674927471*10^(-27) kg" "Neutron rest mass" nil
276 "1.674927471 10^-27 kg (*)")
277 ( mmu "1.883531594*10^(-28) kg" "Muon rest mass" nil
278 "1.883531594 10^-28 kg (*)")
279 ("mmu" "Muon rest mass" nil
280 "1.883531594 10^-28 kg (*)")
281 ( Ryd "10973731.568508 /m" "Rydberg's constant" nil
282 "10973731.568508 /m (*)")
283 ( k "1.38064852*10^(-23) J/K" "Boltzmann's constant" nil
284 "1.38064852 10^-23 J/K (*)")
285 ( sigma "5.670367*10^(-8) W/(m^2 K^4)" "Stefan-Boltzmann constant" nil
286 "5.670367 10^-8 W/(m^2 K^4) (*)")
287 ( σ "sigma" "Stefan-Boltzmann constant" nil
288 "5.670367 10^-8 W/(m^2 K^4) (*)")
289 ( alpha "7.2973525664*10^(-3)" "Fine structure constant" nil
290 "7.2973525664 10^-3 (*)")
291 ( α "alpha" "Fine structure constant" nil
292 "7.2973525664 10^-3 (*)")
293 ( muB "927.4009994*10^(-26) J/T" "Bohr magneton" nil
294 "927.4009994 10^-26 J/T (*)")
295 ( muN "5.050783699*10^(-27) J/T" "Nuclear magneton" nil
296 "5.050783699 10^-27 J/T (*)")
297 ( mue "-928.4764620*10^(-26) J/T" "Electron magnetic moment" nil
298 "-928.4764620 10^-26 J/T (*)")
299 ( mup "1.4106067873*10^(-26) J/T" "Proton magnetic moment" nil
300 "1.4106067873 10^-26 J/T (*)")
301 ( R0 "8.3144598 J/(mol K)" "Molar gas constant" nil
302 "8.3144598 J/(mol K) (*)")
303 ( V0 "22.710947*10^(-3) m^3/mol" "Standard volume of ideal gas" nil
304 "22.710947 10^-3 m^3/mol (*)")
305 ;; Logarithmic units
306 ( Np nil "*Neper")
307 ( dB "(ln(10)/20) Np" "decibel")))
310 (defvar math-additional-units nil
311 "Additional units table for user-defined units.
312 Must be formatted like `math-standard-units'.
313 If you change this, be sure to set `math-units-table' to nil to ensure
314 that the combined units table will be rebuilt.")
316 (defvar math-unit-prefixes
317 '( ( ?Y (^ 10 24) "Yotta" )
318 ( ?Z (^ 10 21) "Zetta" )
319 ( ?E (^ 10 18) "Exa" )
320 ( ?P (^ 10 15) "Peta" )
321 ( ?T (^ 10 12) "Tera" )
322 ( ?G (^ 10 9) "Giga" )
323 ( ?M (^ 10 6) "Mega" )
324 ( ?k (^ 10 3) "Kilo" )
325 ( ?K (^ 10 3) "Kilo" )
326 ( ?h (^ 10 2) "Hecto" )
327 ( ?H (^ 10 2) "Hecto" )
328 ( ?D (^ 10 1) "Deka" )
329 ( 0 (^ 10 0) nil )
330 ( ?d (^ 10 -1) "Deci" )
331 ( ?c (^ 10 -2) "Centi" )
332 ( ?m (^ 10 -3) "Milli" )
333 ( ?u (^ 10 -6) "Micro" )
334 ((^ 10 -6) "Micro" )
335 ( ?n (^ 10 -9) "Nano" )
336 ( ?p (^ 10 -12) "Pico" )
337 ( ?f (^ 10 -15) "Femto" )
338 ( ?a (^ 10 -18) "Atto" )
339 ( ?z (^ 10 -21) "zepto" )
340 ( ?y (^ 10 -24) "yocto" )))
342 (defvar math-standard-units-systems
343 '( ( base nil )
344 ( si ( ( g '(/ (var kg var-kg) 1000) ) ) )
345 ( mks ( ( g '(/ (var kg var-kg) 1000) ) ) )
346 ( cgs ( ( m '(* (var cm var-cm) 100 ) ) ) )))
348 (defvar math-units-table nil
349 "Internal units table.
350 Derived from `math-standard-units' and `math-additional-units'.
351 Entries are (SYMBOL EXPR DOC-STRING TEMP-TYPE BASE-UNITS).")
353 (defvar math-units-table-buffer-valid nil)
355 ;;; Units commands.
357 (defun calc-base-units ()
358 (interactive)
359 (calc-slow-wrapper
360 (let ((calc-autorange-units nil))
361 (calc-enter-result 1 "bsun" (math-simplify-units
362 (math-to-standard-units (calc-top-n 1)
363 nil))))))
365 (defvar calc-ensure-consistent-units)
367 (defun calc-quick-units ()
368 (interactive)
369 (calc-slow-wrapper
370 (let* ((num (- last-command-event ?0))
371 (pos (if (= num 0) 10 num))
372 (units (calc-var-value 'var-Units))
373 (expr (calc-top-n 1)))
374 (unless (and (>= num 0) (<= num 9))
375 (error "Bad unit number"))
376 (unless (math-vectorp units)
377 (error "No \"quick units\" are defined"))
378 (unless (< pos (length units))
379 (error "Unit number %d not defined" pos))
380 (if (math-units-in-expr-p expr nil)
381 (progn
382 (if calc-ensure-consistent-units
383 (math-check-unit-consistency expr (nth pos units)))
384 (calc-enter-result 1 (format "cun%d" num)
385 (math-convert-units expr (nth pos units))))
386 (calc-enter-result 1 (format "*un%d" num)
387 (math-simplify-units
388 (math-mul expr (nth pos units))))))))
390 (defun math-get-standard-units (expr)
391 "Return the standard units in EXPR."
392 (math-simplify-units
393 (math-extract-units
394 (math-to-standard-units expr nil))))
396 (defun math-get-units (expr)
397 "Return the units in EXPR."
398 (math-simplify-units
399 (math-extract-units expr)))
401 (defun math-make-unit-string (expr)
402 "Return EXPR in string form.
403 If EXPR is nil, return nil."
404 (if expr
405 (let ((cexpr (math-compose-expr expr 0)))
406 (replace-regexp-in-string
407 " / " "/"
408 (if (stringp cexpr)
409 cexpr
410 (math-composition-to-string cexpr))))))
412 (defvar math-default-units-table
413 (make-hash-table :test 'equal)
414 "A table storing previously converted units.")
416 (defun math-get-default-units (expr)
417 "Get default units to use when converting the units in EXPR."
418 (let* ((units (math-get-units expr))
419 (standard-units (math-get-standard-units expr))
420 (default-units (gethash
421 standard-units
422 math-default-units-table)))
423 (if (equal units (car default-units))
424 (math-make-unit-string (cadr default-units))
425 (math-make-unit-string (car default-units)))))
427 (defun math-put-default-units (expr &optional comp std)
428 "Put the units in EXPR in the default units table.
429 If COMP or STD is non-nil, put that in the units table instead."
430 (let* ((new-units (or comp std (math-get-units expr)))
431 (standard-units (math-get-standard-units
432 (cond
433 (comp (math-simplify-units expr))
434 (std expr)
435 (t new-units))))
436 (default-units (gethash standard-units math-default-units-table)))
437 (unless (eq standard-units 1)
438 (cond
439 ((not default-units)
440 (puthash standard-units (list new-units) math-default-units-table))
441 ((not (equal new-units (car default-units)))
442 (puthash standard-units
443 (list new-units (car default-units))
444 math-default-units-table))))))
446 (defvar calc-allow-units-as-numbers t)
448 (defun calc-convert-units (&optional old-units new-units)
449 (interactive)
450 (calc-slow-wrapper
451 (let ((expr (calc-top-n 1))
452 (uoldname nil)
453 (unitscancel nil)
454 (nouold nil)
455 unew
456 units
457 defunits)
458 (if (or (not (math-units-in-expr-p expr t))
459 (setq unitscancel (and
460 (if (get 'calc-allow-units-as-numbers 'saved-value)
461 (car (get 'calc-allow-units-as-numbers 'saved-value))
462 calc-allow-units-as-numbers)
463 (eq (math-get-standard-units expr) 1))))
464 (let ((uold (or old-units
465 (progn
466 (setq uoldname
467 (if unitscancel
468 (read-string
469 "(The expression is unitless when simplified) Old Units: ")
470 (read-string "Old units: ")))
471 (if (equal uoldname "")
472 (progn
473 (setq nouold unitscancel)
474 (setq uoldname "1")
476 (if (string-match "\\` */" uoldname)
477 (setq uoldname (concat "1" uoldname)))
478 (math-read-expr uoldname))))))
479 (unless (math-units-in-expr-p uold t)
480 (error "No units specified"))
481 (when (eq (car-safe uold) 'error)
482 (error "Bad format in units expression: %s" (nth 1 uold)))
483 (setq expr (math-mul expr uold))))
484 (setq defunits (math-get-default-units expr))
485 (unless new-units
486 (setq new-units
487 (read-string (concat
488 (if (and uoldname (not nouold))
489 (concat "Old units: "
490 uoldname
491 ", new units")
492 "New units")
493 (if defunits
494 (concat
495 " (default "
496 defunits
497 "): ")
498 ": "))))
499 (if (and
500 (string= new-units "")
501 defunits)
502 (setq new-units defunits)))
503 (when (string-match "\\` */" new-units)
504 (setq new-units (concat "1" new-units)))
505 (setq units (math-read-expr new-units))
506 (when (eq (car-safe units) 'error)
507 (error "Bad format in units expression: %s" (nth 2 units)))
508 (if calc-ensure-consistent-units
509 (math-check-unit-consistency expr units))
510 (let ((unew (math-units-in-expr-p units t))
511 (std (and (eq (car-safe units) 'var)
512 (assq (nth 1 units) math-standard-units-systems)))
513 (comp (eq (car-safe units) '+)))
514 (unless (or unew std)
515 (error "No units specified"))
516 (let* ((noold (and uoldname (not (equal uoldname "1"))))
517 (res
518 (if std
519 (math-simplify-units (math-to-standard-units expr (nth 1 std)))
520 (math-convert-units expr units noold))))
521 (unless std
522 (math-put-default-units (if noold units res) (if comp units)))
523 (calc-enter-result 1 "cvun" res))))))
525 (defun calc-convert-exact-units ()
526 (interactive)
527 (calc-slow-wrapper
528 (let* ((expr (calc-top-n 1)))
529 (unless (math-units-in-expr-p expr t)
530 (error "No units in expression."))
531 (let* ((old-units (math-extract-units expr))
532 (defunits (math-get-default-units expr))
533 units
534 (new-units
535 (read-string (concat "New units"
536 (if defunits
537 (concat
538 " (default "
539 defunits
540 "): ")
541 ": ")))))
542 (if (and
543 (string= new-units "")
544 defunits)
545 (setq new-units defunits))
546 (setq units (math-read-expr new-units))
547 (when (eq (car-safe units) 'error)
548 (error "Bad format in units expression: %s" (nth 2 units)))
549 (math-check-unit-consistency old-units units)
550 (let ((res
551 (list '* (math-mul (math-remove-units expr)
552 (math-simplify-units
553 (math-to-standard-units (list '/ old-units units) nil)))
554 units)))
555 (calc-enter-result 1 "cvxu" res))))))
557 (defun calc-autorange-units (arg)
558 (interactive "P")
559 (calc-wrapper
560 (calc-change-mode 'calc-autorange-units arg nil t)
561 (message (if calc-autorange-units
562 "Adjusting target unit prefix automatically"
563 "Using target units exactly"))))
565 (defun calc-convert-temperature (&optional old-units new-units)
566 (interactive)
567 (calc-slow-wrapper
568 (let ((tempunits (delq nil
569 (mapcar
570 (lambda (x)
571 (if (nth 3 x) (car x)))
572 math-standard-units)))
573 (expr (calc-top-n 1))
574 (uold nil)
575 (uoldname nil)
576 unew
577 defunits)
578 (setq uold (or old-units
579 (let ((units (math-single-units-in-expr-p expr)))
580 (if units
581 (if (consp units)
582 (list 'var (car units)
583 (intern (concat "var-"
584 (symbol-name
585 (car units)))))
586 (error "Not a pure temperature expression"))
587 (math-read-expr
588 (setq uoldname (completing-read
589 "Old temperature units: "
590 tempunits)))))))
591 (when (eq (car-safe uold) 'error)
592 (error "Bad format in units expression: %s" (nth 2 uold)))
593 (or (math-units-in-expr-p expr nil)
594 (setq expr (math-mul expr uold)))
595 (setq defunits (math-get-default-units expr))
596 (setq unew (or new-units
597 (completing-read
598 (concat
599 (if uoldname
600 (concat "Old temperature units: "
601 uoldname
602 ", new units")
603 "New temperature units")
604 (if defunits
605 (concat " (default "
606 defunits
607 "): ")
608 ": "))
609 tempunits)))
610 (setq unew (math-read-expr (if (string= unew "") defunits unew)))
611 (when (eq (car-safe unew) 'error)
612 (error "Bad format in units expression: %s" (nth 2 unew)))
613 (math-put-default-units unew)
614 (let ((ntemp (calc-normalize
615 (math-simplify-units
616 (math-convert-temperature expr uold unew
617 uoldname)))))
618 (if (Math-zerop ntemp)
619 (setq ntemp (list '* ntemp unew)))
620 (let ((calc-simplify-mode 'none))
621 (calc-enter-result 1 "cvtm" ntemp))))))
623 (defun calc-remove-units ()
624 (interactive)
625 (calc-slow-wrapper
626 (calc-enter-result 1 "rmun" (math-simplify-units
627 (math-remove-units (calc-top-n 1))))))
629 (defun calc-extract-units ()
630 (interactive)
631 (calc-slow-wrapper
632 (calc-enter-result 1 "exun" (math-simplify-units
633 (math-extract-units (calc-top-n 1))))))
635 ;; The variables calc-num-units and calc-den-units are local to
636 ;; calc-explain-units, but are used by calc-explain-units-rec,
637 ;; which is called by calc-explain-units.
638 (defvar calc-num-units)
639 (defvar calc-den-units)
641 (defun calc-explain-units ()
642 (interactive)
643 (calc-wrapper
644 (let ((calc-num-units nil)
645 (calc-den-units nil))
646 (calc-explain-units-rec (calc-top-n 1) 1)
647 (and calc-den-units (string-match "^[^(].* .*[^)]$" calc-den-units)
648 (setq calc-den-units (concat "(" calc-den-units ")")))
649 (if calc-num-units
650 (if calc-den-units
651 (message "%s per %s" calc-num-units calc-den-units)
652 (message "%s" calc-num-units))
653 (if calc-den-units
654 (message "1 per %s" calc-den-units)
655 (message "No units in expression"))))))
657 (defun calc-explain-units-rec (expr pow)
658 (let ((u (math-check-unit-name expr))
659 pos)
660 (if (and u (not (math-zerop pow)))
661 (let ((name (or (nth 2 u) (symbol-name (car u)))))
662 (if (eq (aref name 0) ?\*)
663 (setq name (substring name 1)))
664 (if (string-match "[^a-zA-Zα-ωΑ-Ω0-9']" name)
665 (if (string-match "^[a-zA-Zα-ωΑ-Ω0-9' ()]*$" name)
666 (while (setq pos (string-match "[ ()]" name))
667 (setq name (concat (substring name 0 pos)
668 (if (eq (aref name pos) 32) "-" "")
669 (substring name (1+ pos)))))
670 (setq name (concat "(" name ")"))))
671 (or (eq (nth 1 expr) (car u))
672 (setq name (concat (nth 2 (assq (aref (symbol-name
673 (nth 1 expr)) 0)
674 math-unit-prefixes))
675 (if (and (string-match "[^a-zA-Zα-ωΑ-Ω0-9']" name)
676 (not (memq (car u) '(mHg gf))))
677 (concat "-" name)
678 (downcase name)))))
679 (cond ((or (math-equal-int pow 1)
680 (math-equal-int pow -1)))
681 ((or (math-equal-int pow 2)
682 (math-equal-int pow -2))
683 (if (equal (nth 4 u) '((m . 1)))
684 (setq name (concat "Square-" name))
685 (setq name (concat name "-squared"))))
686 ((or (math-equal-int pow 3)
687 (math-equal-int pow -3))
688 (if (equal (nth 4 u) '((m . 1)))
689 (setq name (concat "Cubic-" name))
690 (setq name (concat name "-cubed"))))
692 (setq name (concat name "^"
693 (math-format-number (math-abs pow))))))
694 (if (math-posp pow)
695 (setq calc-num-units (if calc-num-units
696 (concat calc-num-units " " name)
697 name))
698 (setq calc-den-units (if calc-den-units
699 (concat calc-den-units " " name)
700 name))))
701 (cond ((eq (car-safe expr) '*)
702 (calc-explain-units-rec (nth 1 expr) pow)
703 (calc-explain-units-rec (nth 2 expr) pow))
704 ((eq (car-safe expr) '/)
705 (calc-explain-units-rec (nth 1 expr) pow)
706 (calc-explain-units-rec (nth 2 expr) (- pow)))
707 ((memq (car-safe expr) '(neg + -))
708 (calc-explain-units-rec (nth 1 expr) pow))
709 ((and (eq (car-safe expr) '^)
710 (math-realp (nth 2 expr)))
711 (calc-explain-units-rec (nth 1 expr)
712 (math-mul pow (nth 2 expr))))))))
714 (defun calc-simplify-units ()
715 (interactive)
716 (calc-slow-wrapper
717 (calc-with-default-simplification
718 (calc-enter-result 1 "smun" (math-simplify-units (calc-top-n 1))))))
720 (defun calc-view-units-table (n)
721 (interactive "P")
722 (and n (setq math-units-table-buffer-valid nil))
723 (let ((win (get-buffer-window "*Units Table*")))
724 (if (and win
725 math-units-table
726 math-units-table-buffer-valid)
727 (progn
728 (bury-buffer (window-buffer win))
729 (let ((curwin (selected-window)))
730 (select-window win)
731 (switch-to-buffer nil)
732 (select-window curwin)))
733 (math-build-units-table-buffer nil))))
735 (defun calc-enter-units-table (n)
736 (interactive "P")
737 (and n (setq math-units-table-buffer-valid nil))
738 (math-build-units-table-buffer t)
739 (message "%s" (substitute-command-keys "Type \\[calc] to return to the Calculator")))
741 (defun calc-define-unit (uname desc &optional disp)
742 (interactive "SDefine unit name: \nsDescription: \nP")
743 (if disp (setq disp (read-string "Display definition: ")))
744 (calc-wrapper
745 (let ((form (calc-top-n 1))
746 (unit (assq uname math-additional-units)))
747 (or unit
748 (setq math-additional-units
749 (cons (setq unit (list uname nil nil nil nil))
750 math-additional-units)
751 math-units-table nil))
752 (setcar (cdr unit) (and (not (and (eq (car-safe form) 'var)
753 (eq (nth 1 form) uname)))
754 (not (math-equal-int form 1))
755 (math-format-flat-expr form 0)))
756 (setcar (cdr (cdr unit)) (and (not (equal desc ""))
757 desc))
758 (if disp
759 (setcar (cdr (cdr (cdr (cdr unit)))) disp))))
760 (calc-invalidate-units-table))
762 (defun calc-undefine-unit (uname)
763 (interactive "SUndefine unit name: ")
764 (calc-wrapper
765 (let ((unit (assq uname math-additional-units)))
766 (or unit
767 (if (assq uname math-standard-units)
768 (error "\"%s\" is a predefined unit name" uname)
769 (error "Unit name \"%s\" not found" uname)))
770 (setq math-additional-units (delq unit math-additional-units)
771 math-units-table nil)))
772 (calc-invalidate-units-table))
774 (defun calc-invalidate-units-table ()
775 (setq math-units-table nil)
776 (let ((buf (get-buffer "*Units Table*")))
777 (and buf
778 (with-current-buffer buf
779 (save-excursion
780 (goto-char (point-min))
781 (if (looking-at "Calculator Units Table")
782 (let ((inhibit-read-only t))
783 (insert "(Obsolete) "))))))))
785 (defun calc-get-unit-definition (uname)
786 (interactive "SGet definition for unit: ")
787 (calc-wrapper
788 (math-build-units-table)
789 (let ((unit (assq uname math-units-table)))
790 (or unit
791 (error "Unit name \"%s\" not found" uname))
792 (let ((msg (nth 2 unit)))
793 (if (stringp msg)
794 (if (string-match "^\\*" msg)
795 (setq msg (substring msg 1)))
796 (setq msg (symbol-name uname)))
797 (if (nth 1 unit)
798 (progn
799 (calc-enter-result 0 "ugdf" (nth 1 unit))
800 (message "Derived unit: %s" msg))
801 (calc-enter-result 0 "ugdf" (list 'var uname
802 (intern
803 (concat "var-"
804 (symbol-name uname)))))
805 (message "Base unit: %s" msg))))))
807 (defun calc-permanent-units ()
808 (interactive)
809 (calc-wrapper
810 (let (pos)
811 (set-buffer (find-file-noselect (substitute-in-file-name
812 calc-settings-file)))
813 (goto-char (point-min))
814 (if (and (search-forward ";;; Custom units stored by Calc" nil t)
815 (progn
816 (beginning-of-line)
817 (setq pos (point))
818 (search-forward "\n;;; End of custom units" nil t)))
819 (progn
820 (beginning-of-line)
821 (forward-line 1)
822 (delete-region pos (point)))
823 (goto-char (point-max))
824 (insert "\n\n")
825 (forward-char -1))
826 (insert ";;; Custom units stored by Calc on " (current-time-string) "\n")
827 (if math-additional-units
828 (progn
829 (insert "(setq math-additional-units '(\n")
830 (let ((list math-additional-units))
831 (while list
832 (insert " (" (symbol-name (car (car list))) " "
833 (if (nth 1 (car list))
834 (if (stringp (nth 1 (car list)))
835 (prin1-to-string (nth 1 (car list)))
836 (prin1-to-string (math-format-flat-expr
837 (nth 1 (car list)) 0)))
838 "nil")
840 (prin1-to-string (nth 2 (car list)))
841 ")\n")
842 (setq list (cdr list))))
843 (insert "))\n"))
844 (insert ";;; (no custom units defined)\n"))
845 (insert ";;; End of custom units\n")
846 (save-buffer))))
849 ;; The variable math-cu-unit-list is local to math-build-units-table,
850 ;; but is used by math-compare-unit-names, which is called (indirectly)
851 ;; by math-build-units-table.
852 ;; math-cu-unit-list is also local to math-convert-units, but is used
853 ;; by math-convert-units-rec, which is called by math-convert-units.
854 (defvar math-cu-unit-list)
856 (defun math-build-units-table ()
857 (or math-units-table
858 (let* ((combined-units (append math-additional-units
859 math-standard-units))
860 (math-cu-unit-list (mapcar 'car combined-units))
861 tab)
862 (message "Building units table...")
863 (setq math-units-table-buffer-valid nil)
864 (setq tab (mapcar (function
865 (lambda (x)
866 (list (car x)
867 (and (nth 1 x)
868 (if (stringp (nth 1 x))
869 (let ((exp (math-read-plain-expr
870 (nth 1 x))))
871 (if (eq (car-safe exp) 'error)
872 (error "Format error in definition of %s in units table: %s"
873 (car x) (nth 2 exp))
874 exp))
875 (nth 1 x)))
876 (nth 2 x)
877 (nth 3 x)
878 (and (not (nth 1 x))
879 (list (cons (car x) 1)))
880 (nth 4 x))))
881 combined-units))
882 (let ((math-units-table tab))
883 (mapc 'math-find-base-units tab))
884 (message "Building units table...done")
885 (setq math-units-table tab))))
887 ;; The variables math-fbu-base and math-fbu-entry are local to
888 ;; math-find-base-units, but are used by math-find-base-units-rec,
889 ;; which is called by math-find-base-units.
890 (defvar math-fbu-base)
891 (defvar math-fbu-entry)
893 (defun math-find-base-units (math-fbu-entry)
894 (if (eq (nth 4 math-fbu-entry) 'boom)
895 (error "Circular definition involving unit %s" (car math-fbu-entry)))
896 (or (nth 4 math-fbu-entry)
897 (let (math-fbu-base)
898 (setcar (nthcdr 4 math-fbu-entry) 'boom)
899 (math-find-base-units-rec (nth 1 math-fbu-entry) 1)
900 '(or math-fbu-base
901 (error "Dimensionless definition for unit %s" (car math-fbu-entry)))
902 (while (eq (cdr (car math-fbu-base)) 0)
903 (setq math-fbu-base (cdr math-fbu-base)))
904 (let ((b math-fbu-base))
905 (while (cdr b)
906 (if (eq (cdr (car (cdr b))) 0)
907 (setcdr b (cdr (cdr b)))
908 (setq b (cdr b)))))
909 (setq math-fbu-base (sort math-fbu-base 'math-compare-unit-names))
910 (setcar (nthcdr 4 math-fbu-entry) math-fbu-base)
911 math-fbu-base)))
913 (defun math-compare-unit-names (a b)
914 (memq (car b) (cdr (memq (car a) math-cu-unit-list))))
916 (defun math-find-base-units-rec (expr pow)
917 (let ((u (math-check-unit-name expr)))
918 (cond (u
919 (let ((ulist (math-find-base-units u)))
920 (while ulist
921 (let ((p (* (cdr (car ulist)) pow))
922 (old (assq (car (car ulist)) math-fbu-base)))
923 (if old
924 (setcdr old (+ (cdr old) p))
925 (setq math-fbu-base
926 (cons (cons (car (car ulist)) p) math-fbu-base))))
927 (setq ulist (cdr ulist)))))
928 ((math-scalarp expr))
929 ((and (eq (car expr) '^)
930 (integerp (nth 2 expr)))
931 (math-find-base-units-rec (nth 1 expr) (* pow (nth 2 expr))))
932 ((eq (car expr) '*)
933 (math-find-base-units-rec (nth 1 expr) pow)
934 (math-find-base-units-rec (nth 2 expr) pow))
935 ((eq (car expr) '/)
936 (math-find-base-units-rec (nth 1 expr) pow)
937 (math-find-base-units-rec (nth 2 expr) (- pow)))
938 ((eq (car expr) 'neg)
939 (math-find-base-units-rec (nth 1 expr) pow))
940 ((eq (car expr) '+)
941 (math-find-base-units-rec (nth 1 expr) pow))
942 ((eq (car expr) 'var)
943 (or (eq (nth 1 expr) 'pi)
944 (error "Unknown name %s in defining expression for unit %s"
945 (nth 1 expr) (car math-fbu-entry))))
946 ((equal expr '(calcFunc-ln 10)))
947 (t (error "Malformed defining expression for unit %s" (car math-fbu-entry))))))
950 (defun math-units-in-expr-p (expr sub-exprs)
951 (and (consp expr)
952 (if (eq (car expr) 'var)
953 (math-check-unit-name expr)
954 (if (eq (car expr) 'neg)
955 (math-units-in-expr-p (nth 1 expr) sub-exprs)
956 (and (or sub-exprs
957 (memq (car expr) '(* / ^)))
958 (or (math-units-in-expr-p (nth 1 expr) sub-exprs)
959 (math-units-in-expr-p (nth 2 expr) sub-exprs)))))))
961 (defun math-only-units-in-expr-p (expr)
962 (and (consp expr)
963 (if (eq (car expr) 'var)
964 (math-check-unit-name expr)
965 (if (memq (car expr) '(* /))
966 (and (math-only-units-in-expr-p (nth 1 expr))
967 (math-only-units-in-expr-p (nth 2 expr)))
968 (and (eq (car expr) '^)
969 (and (math-only-units-in-expr-p (nth 1 expr))
970 (math-realp (nth 2 expr))))))))
972 (defun math-single-units-in-expr-p (expr)
973 (cond ((math-scalarp expr) nil)
974 ((eq (car expr) 'var)
975 (math-check-unit-name expr))
976 ((eq (car expr) 'neg)
977 (math-single-units-in-expr-p (nth 1 expr)))
978 ((eq (car expr) '*)
979 (let ((u1 (math-single-units-in-expr-p (nth 1 expr)))
980 (u2 (math-single-units-in-expr-p (nth 2 expr))))
981 (or (and u1 u2 'wrong)
983 u2)))
984 ((eq (car expr) '/)
985 (if (math-units-in-expr-p (nth 2 expr) nil)
986 'wrong
987 (math-single-units-in-expr-p (nth 1 expr))))
988 (t 'wrong)))
990 (defun math-consistent-units-p (expr newunits)
991 "Non-nil if EXPR and NEWUNITS have consistent units."
993 (and (eq (car-safe newunits) 'var)
994 (assq (nth 1 newunits) math-standard-units-systems))
995 (math-numberp (math-get-units (math-to-standard-units (list '/ expr newunits) nil)))))
997 (defun math-check-unit-consistency (expr units)
998 "Give an error if EXPR and UNITS do not have consistent units."
999 (unless (math-consistent-units-p expr units)
1000 (error "New units (%s) are inconsistent with current units (%s)"
1001 (math-format-value units)
1002 (math-format-value (math-get-units expr)))))
1004 (defun math-check-unit-name (v)
1005 (and (eq (car-safe v) 'var)
1006 (or (assq (nth 1 v) (or math-units-table (math-build-units-table)))
1007 (let ((name (symbol-name (nth 1 v))))
1008 (and (> (length name) 1)
1009 (assq (aref name 0) math-unit-prefixes)
1010 (or (assq (intern (substring name 1)) math-units-table)
1011 (and (eq (aref name 0) ?M)
1012 (> (length name) 3)
1013 (eq (aref name 1) ?e)
1014 (eq (aref name 2) ?g)
1015 (assq (intern (substring name 3))
1016 math-units-table))))))))
1018 ;; The variable math-which-standard is local to math-to-standard-units,
1019 ;; but is used by math-to-standard-rec, which is called by
1020 ;; math-to-standard-units.
1021 (defvar math-which-standard)
1023 (defun math-to-standard-units (expr math-which-standard)
1024 (math-to-standard-rec expr))
1026 (defun math-to-standard-rec (expr)
1027 (if (eq (car-safe expr) 'var)
1028 (let ((u (math-check-unit-name expr))
1029 (base (nth 1 expr)))
1030 (if u
1031 (progn
1032 (if (nth 1 u)
1033 (setq expr (math-to-standard-rec (nth 1 u)))
1034 (let ((st (assq (car u) math-which-standard)))
1035 (if st
1036 (setq expr (nth 1 st))
1037 (setq expr (list 'var (car u)
1038 (intern (concat "var-"
1039 (symbol-name
1040 (car u)))))))))
1041 (or (null u)
1042 (eq base (car u))
1043 (setq expr (list '*
1044 (nth 1 (assq (aref (symbol-name base) 0)
1045 math-unit-prefixes))
1046 expr)))
1047 expr)
1048 (if (eq base 'pi)
1049 (math-pi)
1050 expr)))
1051 (if (or
1052 (Math-primp expr)
1053 (and (eq (car-safe expr) 'calcFunc-subscr)
1054 (eq (car-safe (nth 1 expr)) 'var)))
1055 expr
1056 (cons (car expr)
1057 (mapcar 'math-to-standard-rec (cdr expr))))))
1059 (defun math-apply-units (expr units ulist &optional pure)
1060 (setq expr (math-simplify-units expr))
1061 (if ulist
1062 (let ((new 0)
1063 value)
1064 (or (math-numberp expr)
1065 (error "Incompatible units"))
1066 (while (cdr ulist)
1067 (setq value (math-div expr (nth 1 (car ulist)))
1068 value (math-floor (let ((calc-internal-prec
1069 (1- calc-internal-prec)))
1070 (math-normalize value)))
1071 new (math-add new (math-mul value (car (car ulist))))
1072 expr (math-sub expr (math-mul value (nth 1 (car ulist))))
1073 ulist (cdr ulist)))
1074 (math-add new (math-mul (math-div expr (nth 1 (car ulist)))
1075 (car (car ulist)))))
1076 (if pure
1077 expr
1078 (math-simplify-units (list '* expr units)))))
1080 (defvar math-decompose-units-cache nil)
1081 (defun math-decompose-units (units)
1082 (let ((u (math-check-unit-name units)))
1083 (and u (eq (car-safe (nth 1 u)) '+)
1084 (setq units (nth 1 u))))
1085 (setq units (calcFunc-expand units))
1086 (and (eq (car-safe units) '+)
1087 (let ((entry (list units calc-internal-prec calc-prefer-frac)))
1088 (or (equal entry (car math-decompose-units-cache))
1089 (let ((ulist nil)
1090 (utemp units)
1091 qty unit)
1092 (while (eq (car-safe utemp) '+)
1093 (setq ulist (cons (math-decompose-unit-part (nth 2 utemp))
1094 ulist)
1095 utemp (nth 1 utemp)))
1096 (setq ulist (cons (math-decompose-unit-part utemp) ulist)
1097 utemp ulist)
1098 (while (setq utemp (cdr utemp))
1099 (unless (equal (nth 2 (car utemp)) (nth 2 (car ulist)))
1100 (error "Inconsistent units in sum")))
1101 (setq math-decompose-units-cache
1102 (cons entry
1103 (sort ulist
1104 (function
1105 (lambda (x y)
1106 (not (Math-lessp (nth 1 x)
1107 (nth 1 y))))))))))
1108 (cdr math-decompose-units-cache))))
1110 (defun math-decompose-unit-part (unit)
1111 (cons unit
1112 (math-is-multiple (math-simplify-units (math-to-standard-units
1113 unit nil))
1114 t)))
1116 ;; The variable math-fcu-u is local to math-find-compatible-unit,
1117 ;; but is used by math-find-compatible-rec which is called by
1118 ;; math-find-compatible-unit.
1119 (defvar math-fcu-u)
1121 (defun math-find-compatible-unit (expr unit)
1122 (let ((math-fcu-u (math-check-unit-name unit)))
1123 (if math-fcu-u
1124 (math-find-compatible-unit-rec expr 1))))
1126 (defun math-find-compatible-unit-rec (expr pow)
1127 (cond ((eq (car-safe expr) '*)
1128 (or (math-find-compatible-unit-rec (nth 1 expr) pow)
1129 (math-find-compatible-unit-rec (nth 2 expr) pow)))
1130 ((eq (car-safe expr) '/)
1131 (or (math-find-compatible-unit-rec (nth 1 expr) pow)
1132 (math-find-compatible-unit-rec (nth 2 expr) (- pow))))
1133 ((eq (car-safe expr) 'neg)
1134 (math-find-compatible-unit-rec (nth 1 expr) pow))
1135 ((and (eq (car-safe expr) '^)
1136 (integerp (nth 2 expr)))
1137 (math-find-compatible-unit-rec (nth 1 expr) (* pow (nth 2 expr))))
1139 (let ((u2 (math-check-unit-name expr)))
1140 (if (equal (nth 4 math-fcu-u) (nth 4 u2))
1141 (cons expr pow))))))
1143 ;; The variables math-cu-new-units and math-cu-pure are local to
1144 ;; math-convert-units, but are used by math-convert-units-rec,
1145 ;; which is called by math-convert-units.
1146 (defvar math-cu-new-units)
1147 (defvar math-cu-pure)
1149 (defun math-convert-units (expr math-cu-new-units &optional math-cu-pure)
1150 (if (eq (car-safe math-cu-new-units) 'var)
1151 (let ((unew (assq (nth 1 math-cu-new-units)
1152 (math-build-units-table))))
1153 (if (eq (car-safe (nth 1 unew)) '+)
1154 (setq math-cu-new-units (nth 1 unew)))))
1155 (math-with-extra-prec 2
1156 (let ((compat (and (not math-cu-pure)
1157 (math-find-compatible-unit expr math-cu-new-units)))
1158 (math-cu-unit-list nil)
1159 (math-combining-units nil))
1160 (if compat
1161 (math-simplify-units
1162 (math-mul (math-mul (math-simplify-units
1163 (math-div expr (math-pow (car compat)
1164 (cdr compat))))
1165 (math-pow math-cu-new-units (cdr compat)))
1166 (math-simplify-units
1167 (math-to-standard-units
1168 (math-pow (math-div (car compat) math-cu-new-units)
1169 (cdr compat))
1170 nil))))
1171 (when (setq math-cu-unit-list (math-decompose-units math-cu-new-units))
1172 (setq math-cu-new-units (nth 2 (car math-cu-unit-list))))
1173 (when (eq (car-safe expr) '+)
1174 (setq expr (math-simplify-units expr)))
1175 (if (math-units-in-expr-p expr t)
1176 (math-convert-units-rec expr)
1177 (math-apply-units (math-to-standard-units
1178 (list '/ expr math-cu-new-units) nil)
1179 math-cu-new-units math-cu-unit-list math-cu-pure))))))
1181 (defun math-convert-units-rec (expr)
1182 (if (math-units-in-expr-p expr nil)
1183 (math-apply-units (math-to-standard-units
1184 (list '/ expr math-cu-new-units) nil)
1185 math-cu-new-units math-cu-unit-list math-cu-pure)
1186 (if (Math-primp expr)
1187 expr
1188 (cons (car expr)
1189 (mapcar 'math-convert-units-rec (cdr expr))))))
1191 (defun math-convert-temperature (expr old new &optional pure)
1192 (let* ((units (math-single-units-in-expr-p expr))
1193 (uold (if old
1194 (if (or (null units)
1195 (equal (nth 1 old) (car units)))
1196 (math-check-unit-name old)
1197 (error "Inconsistent temperature units"))
1198 units))
1199 (unew (math-check-unit-name new)))
1200 (unless (and (consp unew) (nth 3 unew))
1201 (error "Not a valid temperature unit"))
1202 (unless (and (consp uold) (nth 3 uold))
1203 (error "Not a pure temperature expression"))
1204 (let ((v (car uold)))
1205 (setq expr (list '/ expr (list 'var v
1206 (intern (concat "var-"
1207 (symbol-name v)))))))
1208 (or (eq (nth 3 uold) (nth 3 unew))
1209 (cond ((eq (nth 3 uold) 'K)
1210 (setq expr (list '- expr '(/ 27315 100)))
1211 (if (eq (nth 3 unew) 'F)
1212 (setq expr (list '+ (list '* expr '(/ 9 5)) 32))))
1213 ((eq (nth 3 uold) 'C)
1214 (if (eq (nth 3 unew) 'F)
1215 (setq expr (list '+ (list '* expr '(/ 9 5)) 32))
1216 (setq expr (list '+ expr '(/ 27315 100)))))
1218 (setq expr (list '* (list '- expr 32) '(/ 5 9)))
1219 (if (eq (nth 3 unew) 'K)
1220 (setq expr (list '+ expr '(/ 27315 100)))))))
1221 (if pure
1222 expr
1223 (list '* expr new))))
1227 (defun math-simplify-units (a)
1228 (let ((math-simplifying-units t)
1229 (calc-matrix-mode 'scalar))
1230 (math-simplify a)))
1231 (defalias 'calcFunc-usimplify 'math-simplify-units)
1233 ;; The function created by math-defsimplify uses the variable
1234 ;; math-simplify-expr, and so is used by functions in math-defsimplify
1235 (defvar math-simplify-expr)
1237 (math-defsimplify (+ -)
1238 (and math-simplifying-units
1239 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1240 (let* ((units (math-extract-units (nth 1 math-simplify-expr)))
1241 (ratio (math-simplify (math-to-standard-units
1242 (list '/ (nth 2 math-simplify-expr) units) nil))))
1243 (if (math-units-in-expr-p ratio nil)
1244 (progn
1245 (calc-record-why "*Inconsistent units" math-simplify-expr)
1246 math-simplify-expr)
1247 (list '* (math-add (math-remove-units (nth 1 math-simplify-expr))
1248 (if (eq (car math-simplify-expr) '-)
1249 (math-neg ratio) ratio))
1250 units)))))
1252 (math-defsimplify *
1253 (math-simplify-units-prod))
1255 (defun math-simplify-units-prod ()
1256 (and math-simplifying-units
1257 calc-autorange-units
1258 (Math-realp (nth 1 math-simplify-expr))
1259 (let* ((num (math-float (nth 1 math-simplify-expr)))
1260 (xpon (calcFunc-xpon num))
1261 (unitp (cdr (cdr math-simplify-expr)))
1262 (unit (car unitp))
1263 (pow (if (eq (car math-simplify-expr) '*) 1 -1))
1265 (and (eq (car-safe unit) '*)
1266 (setq unitp (cdr unit)
1267 unit (car unitp)))
1268 (and (eq (car-safe unit) '^)
1269 (integerp (nth 2 unit))
1270 (setq pow (* pow (nth 2 unit))
1271 unitp (cdr unit)
1272 unit (car unitp)))
1273 (and (setq u (math-check-unit-name unit))
1274 (integerp xpon)
1275 (or (< xpon 0)
1276 (>= xpon (if (eq (car u) 'm) 1 3)))
1277 (let* ((uxpon 0)
1278 (pref (if (< pow 0)
1279 (reverse math-unit-prefixes)
1280 math-unit-prefixes))
1281 (p pref)
1282 pxpon pname)
1283 (or (eq (car u) (nth 1 unit))
1284 (setq uxpon (* pow
1285 (nth 2 (nth 1 (assq
1286 (aref (symbol-name
1287 (nth 1 unit)) 0)
1288 math-unit-prefixes))))))
1289 (setq xpon (+ xpon uxpon))
1290 (while (and p
1291 (or (memq (car (car p)) '(?d ?D ?h ?H))
1292 (and (eq (car (car p)) ?c)
1293 (not (eq (car u) 'm)))
1294 (< xpon (setq pxpon (* (nth 2 (nth 1 (car p)))
1295 pow)))
1296 (progn
1297 (setq pname (math-build-var-name
1298 (if (eq (car (car p)) 0)
1299 (car u)
1300 (concat (char-to-string
1301 (car (car p)))
1302 (symbol-name
1303 (car u))))))
1304 (and (/= (car (car p)) 0)
1305 (assq (nth 1 pname)
1306 math-units-table)))))
1307 (setq p (cdr p)))
1308 (and p
1309 (/= pxpon uxpon)
1310 (or (not (eq p pref))
1311 (< xpon (+ pxpon (* (math-abs pow) 3))))
1312 (progn
1313 (setcar (cdr math-simplify-expr)
1314 (let ((calc-prefer-frac nil))
1315 (calcFunc-scf (nth 1 math-simplify-expr)
1316 (- uxpon pxpon))))
1317 (setcar unitp pname)
1318 math-simplify-expr)))))))
1320 (defvar math-try-cancel-units)
1322 (math-defsimplify /
1323 (and math-simplifying-units
1324 (let ((np (cdr math-simplify-expr))
1325 (math-try-cancel-units 0)
1326 n nn)
1327 (setq n (if (eq (car-safe (nth 2 math-simplify-expr)) '*)
1328 (cdr (nth 2 math-simplify-expr))
1329 (nthcdr 2 math-simplify-expr)))
1330 (if (math-realp (car n))
1331 (progn
1332 (setcar (cdr math-simplify-expr) (math-mul (nth 1 math-simplify-expr)
1333 (let ((calc-prefer-frac nil))
1334 (math-div 1 (car n)))))
1335 (setcar n 1)))
1336 (while (eq (car-safe (setq n (car np))) '*)
1337 (math-simplify-units-divisor (cdr n) (cdr (cdr math-simplify-expr)))
1338 (setq np (cdr (cdr n))))
1339 (math-simplify-units-divisor np (cdr (cdr math-simplify-expr)))
1340 (if (eq math-try-cancel-units 0)
1341 (let* ((math-simplifying-units nil)
1342 (base (math-simplify
1343 (math-to-standard-units math-simplify-expr nil))))
1344 (if (Math-numberp base)
1345 (setq math-simplify-expr base))))
1346 (if (eq (car-safe math-simplify-expr) '/)
1347 (math-simplify-units-prod))
1348 math-simplify-expr)))
1350 (defun math-simplify-units-divisor (np dp)
1351 (let ((n (car np))
1352 d dd temp)
1353 (while (eq (car-safe (setq d (car dp))) '*)
1354 (when (setq temp (math-simplify-units-quotient n (nth 1 d)))
1355 (setcar np (setq n temp))
1356 (setcar (cdr d) 1))
1357 (setq dp (cdr (cdr d))))
1358 (when (setq temp (math-simplify-units-quotient n d))
1359 (setcar np (setq n temp))
1360 (setcar dp 1))))
1362 ;; Simplify, e.g., "in / cm" to "2.54" in a units expression.
1363 (defun math-simplify-units-quotient (n d)
1364 (let ((pow1 1)
1365 (pow2 1))
1366 (when (and (eq (car-safe n) '^)
1367 (integerp (nth 2 n)))
1368 (setq pow1 (nth 2 n) n (nth 1 n)))
1369 (when (and (eq (car-safe d) '^)
1370 (integerp (nth 2 d)))
1371 (setq pow2 (nth 2 d) d (nth 1 d)))
1372 (let ((un (math-check-unit-name n))
1373 (ud (math-check-unit-name d)))
1374 (and un ud
1375 (if (and (equal (nth 4 un) (nth 4 ud))
1376 (eq pow1 pow2))
1377 (if (eq pow1 1)
1378 (math-to-standard-units (list '/ n d) nil)
1379 (list '^ (math-to-standard-units (list '/ n d) nil) pow1))
1380 (let (ud1)
1381 (setq un (nth 4 un)
1382 ud (nth 4 ud))
1383 (while un
1384 (setq ud1 ud)
1385 (while ud1
1386 (and (eq (car (car un)) (car (car ud1)))
1387 (setq math-try-cancel-units
1388 (+ math-try-cancel-units
1389 (- (* (cdr (car un)) pow1)
1390 (* (cdr (car ud)) pow2)))))
1391 (setq ud1 (cdr ud1)))
1392 (setq un (cdr un)))
1393 nil))))))
1395 (math-defsimplify ^
1396 (and math-simplifying-units
1397 (math-realp (nth 2 math-simplify-expr))
1398 (if (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1399 (list (car (nth 1 math-simplify-expr))
1400 (list '^ (nth 1 (nth 1 math-simplify-expr))
1401 (nth 2 math-simplify-expr))
1402 (list '^ (nth 2 (nth 1 math-simplify-expr))
1403 (nth 2 math-simplify-expr)))
1404 (math-simplify-units-pow (nth 1 math-simplify-expr)
1405 (nth 2 math-simplify-expr)))))
1407 (math-defsimplify calcFunc-sqrt
1408 (and math-simplifying-units
1409 (if (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1410 (list (car (nth 1 math-simplify-expr))
1411 (list 'calcFunc-sqrt (nth 1 (nth 1 math-simplify-expr)))
1412 (list 'calcFunc-sqrt (nth 2 (nth 1 math-simplify-expr))))
1413 (math-simplify-units-pow (nth 1 math-simplify-expr) '(frac 1 2)))))
1415 (math-defsimplify (calcFunc-floor
1416 calcFunc-ceil
1417 calcFunc-round
1418 calcFunc-rounde
1419 calcFunc-roundu
1420 calcFunc-trunc
1421 calcFunc-float
1422 calcFunc-frac
1423 calcFunc-abs
1424 calcFunc-clean)
1425 (and math-simplifying-units
1426 (= (length math-simplify-expr) 2)
1427 (if (math-only-units-in-expr-p (nth 1 math-simplify-expr))
1428 (nth 1 math-simplify-expr)
1429 (if (and (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1430 (or (math-only-units-in-expr-p
1431 (nth 1 (nth 1 math-simplify-expr)))
1432 (math-only-units-in-expr-p
1433 (nth 2 (nth 1 math-simplify-expr)))))
1434 (list (car (nth 1 math-simplify-expr))
1435 (cons (car math-simplify-expr)
1436 (cons (nth 1 (nth 1 math-simplify-expr))
1437 (cdr (cdr math-simplify-expr))))
1438 (cons (car math-simplify-expr)
1439 (cons (nth 2 (nth 1 math-simplify-expr))
1440 (cdr (cdr math-simplify-expr)))))))))
1442 (defun math-simplify-units-pow (a pow)
1443 (if (and (eq (car-safe a) '^)
1444 (math-check-unit-name (nth 1 a))
1445 (math-realp (nth 2 a)))
1446 (list '^ (nth 1 a) (math-mul pow (nth 2 a)))
1447 (let* ((u (math-check-unit-name a))
1448 (pf (math-to-simple-fraction pow))
1449 (d (and (eq (car-safe pf) 'frac) (nth 2 pf))))
1450 (and u d
1451 (math-units-are-multiple u d)
1452 (list '^ (math-to-standard-units a nil) pow)))))
1455 (defun math-units-are-multiple (u n)
1456 (setq u (nth 4 u))
1457 (while (and u (= (% (cdr (car u)) n) 0))
1458 (setq u (cdr u)))
1459 (null u))
1461 (math-defsimplify calcFunc-sin
1462 (and math-simplifying-units
1463 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1464 (let ((rad (math-simplify-units
1465 (math-evaluate-expr
1466 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1467 (calc-angle-mode 'rad))
1468 (and (eq (car-safe rad) '*)
1469 (math-realp (nth 1 rad))
1470 (eq (car-safe (nth 2 rad)) 'var)
1471 (eq (nth 1 (nth 2 rad)) 'rad)
1472 (list 'calcFunc-sin (nth 1 rad))))))
1474 (math-defsimplify calcFunc-cos
1475 (and math-simplifying-units
1476 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1477 (let ((rad (math-simplify-units
1478 (math-evaluate-expr
1479 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1480 (calc-angle-mode 'rad))
1481 (and (eq (car-safe rad) '*)
1482 (math-realp (nth 1 rad))
1483 (eq (car-safe (nth 2 rad)) 'var)
1484 (eq (nth 1 (nth 2 rad)) 'rad)
1485 (list 'calcFunc-cos (nth 1 rad))))))
1487 (math-defsimplify calcFunc-tan
1488 (and math-simplifying-units
1489 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1490 (let ((rad (math-simplify-units
1491 (math-evaluate-expr
1492 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1493 (calc-angle-mode 'rad))
1494 (and (eq (car-safe rad) '*)
1495 (math-realp (nth 1 rad))
1496 (eq (car-safe (nth 2 rad)) 'var)
1497 (eq (nth 1 (nth 2 rad)) 'rad)
1498 (list 'calcFunc-tan (nth 1 rad))))))
1500 (math-defsimplify calcFunc-sec
1501 (and math-simplifying-units
1502 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1503 (let ((rad (math-simplify-units
1504 (math-evaluate-expr
1505 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1506 (calc-angle-mode 'rad))
1507 (and (eq (car-safe rad) '*)
1508 (math-realp (nth 1 rad))
1509 (eq (car-safe (nth 2 rad)) 'var)
1510 (eq (nth 1 (nth 2 rad)) 'rad)
1511 (list 'calcFunc-sec (nth 1 rad))))))
1513 (math-defsimplify calcFunc-csc
1514 (and math-simplifying-units
1515 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1516 (let ((rad (math-simplify-units
1517 (math-evaluate-expr
1518 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1519 (calc-angle-mode 'rad))
1520 (and (eq (car-safe rad) '*)
1521 (math-realp (nth 1 rad))
1522 (eq (car-safe (nth 2 rad)) 'var)
1523 (eq (nth 1 (nth 2 rad)) 'rad)
1524 (list 'calcFunc-csc (nth 1 rad))))))
1526 (math-defsimplify calcFunc-cot
1527 (and math-simplifying-units
1528 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1529 (let ((rad (math-simplify-units
1530 (math-evaluate-expr
1531 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1532 (calc-angle-mode 'rad))
1533 (and (eq (car-safe rad) '*)
1534 (math-realp (nth 1 rad))
1535 (eq (car-safe (nth 2 rad)) 'var)
1536 (eq (nth 1 (nth 2 rad)) 'rad)
1537 (list 'calcFunc-cot (nth 1 rad))))))
1540 (defun math-remove-units (expr)
1541 (if (math-check-unit-name expr)
1543 (if (Math-primp expr)
1544 expr
1545 (cons (car expr)
1546 (mapcar 'math-remove-units (cdr expr))))))
1548 (defun math-extract-units (expr)
1549 (cond
1550 ((memq (car-safe expr) '(* /))
1551 (cons (car expr)
1552 (mapcar 'math-extract-units (cdr expr))))
1553 ((eq (car-safe expr) 'neg)
1554 (math-extract-units (nth 1 expr)))
1555 ((eq (car-safe expr) '^)
1556 (list '^ (math-extract-units (nth 1 expr)) (nth 2 expr)))
1557 ((math-check-unit-name expr) expr)
1558 (t 1)))
1560 (defun math-build-units-table-buffer (enter-buffer)
1561 (if (not (and math-units-table math-units-table-buffer-valid
1562 (get-buffer "*Units Table*")))
1563 (let ((buf (get-buffer-create "*Units Table*"))
1564 (uptr (math-build-units-table))
1565 (calc-language (if (eq calc-language 'big) nil calc-language))
1566 (calc-float-format '(float 0))
1567 (calc-group-digits nil)
1568 (calc-number-radix 10)
1569 (calc-twos-complement-mode nil)
1570 (calc-point-char ".")
1571 (std nil)
1572 u name shadowed)
1573 (save-excursion
1574 (message "Formatting units table...")
1575 (set-buffer buf)
1576 (let ((inhibit-read-only t))
1577 (erase-buffer)
1578 (insert "Calculator Units Table:\n\n")
1579 (insert "(All definitions are exact unless marked with an asterisk (*).)\n\n")
1580 (insert "Unit Type Definition Description\n\n")
1581 (while uptr
1582 (setq u (car uptr)
1583 name (nth 2 u))
1584 (when (eq (car u) 'm)
1585 (setq std t))
1586 (setq shadowed (and std (assq (car u) math-additional-units)))
1587 (when (and name
1588 (> (length name) 1)
1589 (eq (aref name 0) ?\*))
1590 (unless (eq uptr math-units-table)
1591 (insert "\n"))
1592 (setq name (substring name 1)))
1593 (insert " ")
1594 (and shadowed (insert "("))
1595 (insert (symbol-name (car u)))
1596 (and shadowed (insert ")"))
1597 (if (nth 3 u)
1598 (progn
1599 (indent-to 10)
1600 (insert (symbol-name (nth 3 u))))
1601 (or std
1602 (progn
1603 (indent-to 10)
1604 (insert "U"))))
1605 (indent-to 14)
1606 (and shadowed (insert "("))
1607 (if (nth 5 u)
1608 (insert (nth 5 u))
1609 (if (nth 1 u)
1610 (insert (math-format-value (nth 1 u) 80))
1611 (insert (symbol-name (car u)))))
1612 (and shadowed (insert ")"))
1613 (indent-to 41)
1614 (insert " ")
1615 (when name
1616 (insert name))
1617 (if shadowed
1618 (insert " (redefined above)")
1619 (unless (nth 1 u)
1620 (insert " (base unit)")))
1621 (insert "\n")
1622 (setq uptr (cdr uptr)))
1623 (insert "\n\nUnit Prefix Table:\n\n")
1624 (setq uptr math-unit-prefixes)
1625 (while uptr
1626 (setq u (car uptr))
1627 (insert " " (char-to-string (car u)))
1628 (if (equal (nth 1 u) (nth 1 (nth 1 uptr)))
1629 (insert " " (char-to-string (car (car (setq uptr (cdr uptr)))))
1630 " ")
1631 (insert " "))
1632 (insert "10^" (int-to-string (nth 2 (nth 1 u))))
1633 (indent-to 15)
1634 (insert " " (nth 2 u) "\n")
1635 (while (eq (car (car (setq uptr (cdr uptr)))) 0)))
1636 (insert "\n\n")
1637 (insert
1638 (format-message
1639 (concat
1640 "(**) When in TeX or LaTeX display mode, the TeX specific unit\n"
1641 "names will not use the `tex' prefix; the unit name for a\n"
1642 "TeX point will be `pt' instead of `texpt', for example.\n"
1643 "To avoid conflicts, the unit names for pint and parsec will\n"
1644 "be `pint' and `parsec' instead of `pt' and `pc'."))))
1645 (special-mode)
1646 (message "Formatting units table...done"))
1647 (setq math-units-table-buffer-valid t)
1648 (let ((oldbuf (current-buffer)))
1649 (set-buffer buf)
1650 (goto-char (point-min))
1651 (set-buffer oldbuf))
1652 (if enter-buffer
1653 (pop-to-buffer buf)
1654 (display-buffer buf)))
1655 (if enter-buffer
1656 (pop-to-buffer (get-buffer "*Units Table*"))
1657 (display-buffer (get-buffer "*Units Table*")))))
1659 ;;; Logarithmic units functions
1661 (defvar math-logunits '((var dB var-dB)
1662 (var Np var-Np)))
1664 (defun math-conditional-apply (fn &rest args)
1665 "Evaluate f(args) unless in symbolic mode.
1666 In symbolic mode, return the list (fn args)."
1667 (if calc-symbolic-mode
1668 (cons fn args)
1669 (apply fn args)))
1671 (defun math-conditional-pow (a b)
1672 "Evaluate a^b unless in symbolic mode.
1673 In symbolic mode, return the list (^ a b)."
1674 (if calc-symbolic-mode
1675 (list '^ a b)
1676 (math-pow a b)))
1678 (defun math-extract-logunits (expr)
1679 (if (memq (car-safe expr) '(* /))
1680 (cons (car expr)
1681 (mapcar 'math-extract-logunits (cdr expr)))
1682 (if (memq (car-safe expr) '(^))
1683 (list '^ (math-extract-logunits (nth 1 expr)) (nth 2 expr))
1684 (if (member expr math-logunits) expr 1))))
1686 (defun math-logunits-add (a b neg power)
1687 (let ((aunit (math-simplify (math-extract-logunits a))))
1688 (if (not (eq (car-safe aunit) 'var))
1689 (calc-record-why "*Improper logarithmic unit" aunit)
1690 (let* ((units (math-extract-units a))
1691 (acoeff (math-simplify (math-remove-units a)))
1692 (bcoeff (math-simplify (math-to-standard-units
1693 (list '/ b units) nil))))
1694 (if (math-units-in-expr-p bcoeff nil)
1695 (calc-record-why "*Inconsistent units" nil)
1696 (if (and neg
1697 (or (math-lessp acoeff bcoeff)
1698 (math-equal acoeff bcoeff)))
1699 (calc-record-why "*Improper coefficients" nil)
1700 (math-mul
1701 (if (equal aunit '(var dB var-dB))
1702 (let ((coef (if power 10 20)))
1703 (math-mul coef
1704 (math-conditional-apply 'calcFunc-log10
1705 (if neg
1706 (math-sub
1707 (math-conditional-pow 10 (math-div acoeff coef))
1708 (math-conditional-pow 10 (math-div bcoeff coef)))
1709 (math-add
1710 (math-conditional-pow 10 (math-div acoeff coef))
1711 (math-conditional-pow 10 (math-div bcoeff coef)))))))
1712 (let ((coef (if power 2 1)))
1713 (math-div
1714 (math-conditional-apply 'calcFunc-ln
1715 (if neg
1716 (math-sub
1717 (math-conditional-apply 'calcFunc-exp (math-mul coef acoeff))
1718 (math-conditional-apply 'calcFunc-exp (math-mul coef bcoeff)))
1719 (math-add
1720 (math-conditional-apply 'calcFunc-exp (math-mul coef acoeff))
1721 (math-conditional-apply 'calcFunc-exp (math-mul coef bcoeff)))))
1722 coef)))
1723 units)))))))
1725 (defun calcFunc-lufadd (a b)
1726 (math-logunits-add a b nil nil))
1728 (defun calcFunc-lupadd (a b)
1729 (math-logunits-add a b nil t))
1731 (defun calcFunc-lufsub (a b)
1732 (math-logunits-add a b t nil))
1734 (defun calcFunc-lupsub (a b)
1735 (math-logunits-add a b t t))
1737 (defun calc-lu-plus (arg)
1738 (interactive "P")
1739 (calc-slow-wrapper
1740 (if (calc-is-inverse)
1741 (if (calc-is-hyperbolic)
1742 (calc-binary-op "lu-" 'calcFunc-lufsub arg)
1743 (calc-binary-op "lu-" 'calcFunc-lupsub arg))
1744 (if (calc-is-hyperbolic)
1745 (calc-binary-op "lu+" 'calcFunc-lufadd arg)
1746 (calc-binary-op "lu+" 'calcFunc-lupadd arg)))))
1748 (defun calc-lu-minus (arg)
1749 (interactive "P")
1750 (calc-slow-wrapper
1751 (if (calc-is-inverse)
1752 (if (calc-is-hyperbolic)
1753 (calc-binary-op "lu+" 'calcFunc-lufadd arg)
1754 (calc-binary-op "lu+" 'calcFunc-lupadd arg))
1755 (if (calc-is-hyperbolic)
1756 (calc-binary-op "lu-" 'calcFunc-lufsub arg)
1757 (calc-binary-op "lu-" 'calcFunc-lupsub arg)))))
1759 (defun math-logunits-mul (a b power)
1760 (let (logunit coef units number)
1761 (cond
1762 ((and
1763 (setq logunit (math-simplify (math-extract-logunits a)))
1764 (eq (car-safe logunit) 'var)
1765 (eq (math-simplify (math-extract-units b)) 1))
1766 (setq coef (math-simplify (math-remove-units a))
1767 units (math-extract-units a)
1768 number b))
1769 ((and
1770 (setq logunit (math-simplify (math-extract-logunits b)))
1771 (eq (car-safe logunit) 'var)
1772 (eq (math-simplify (math-extract-units a)) 1))
1773 (setq coef (math-simplify (math-remove-units b))
1774 units (math-extract-units b)
1775 number a))
1776 (t (setq logunit nil)))
1777 (if logunit
1778 (cond
1779 ((equal logunit '(var dB var-dB))
1780 (math-simplify
1781 (math-mul
1782 (math-add
1783 coef
1784 (math-mul (if power 10 20)
1785 (math-conditional-apply 'calcFunc-log10 number)))
1786 units)))
1788 (math-simplify
1789 (math-mul
1790 (math-add
1791 coef
1792 (math-div (math-conditional-apply 'calcFunc-ln number) (if power 2 1)))
1793 units))))
1794 (calc-record-why "*Improper units" nil))))
1796 (defun math-logunits-divide (a b power)
1797 (let ((logunit (math-simplify (math-extract-logunits a))))
1798 (if (not (eq (car-safe logunit) 'var))
1799 (calc-record-why "*Improper logarithmic unit" logunit)
1800 (if (math-units-in-expr-p b nil)
1801 (calc-record-why "*Improper units quantity" b)
1802 (let* ((units (math-extract-units a))
1803 (coef (math-simplify (math-remove-units a))))
1804 (cond
1805 ((equal logunit '(var dB var-dB))
1806 (math-simplify
1807 (math-mul
1808 (math-sub
1809 coef
1810 (math-mul (if power 10 20)
1811 (math-conditional-apply 'calcFunc-log10 b)))
1812 units)))
1814 (math-simplify
1815 (math-mul
1816 (math-sub
1817 coef
1818 (math-div (math-conditional-apply 'calcFunc-ln b) (if power 2 1)))
1819 units)))))))))
1821 (defun calcFunc-lufmul (a b)
1822 (math-logunits-mul a b nil))
1824 (defun calcFunc-lupmul (a b)
1825 (math-logunits-mul a b t))
1827 (defun calc-lu-times (arg)
1828 (interactive "P")
1829 (calc-slow-wrapper
1830 (if (calc-is-inverse)
1831 (if (calc-is-hyperbolic)
1832 (calc-binary-op "lu/" 'calcFunc-lufdiv arg)
1833 (calc-binary-op "lu/" 'calcFunc-lupdiv arg))
1834 (if (calc-is-hyperbolic)
1835 (calc-binary-op "lu*" 'calcFunc-lufmul arg)
1836 (calc-binary-op "lu*" 'calcFunc-lupmul arg)))))
1838 (defun calcFunc-lufdiv (a b)
1839 (math-logunits-divide a b nil))
1841 (defun calcFunc-lupdiv (a b)
1842 (math-logunits-divide a b t))
1844 (defun calc-lu-divide (arg)
1845 (interactive "P")
1846 (calc-slow-wrapper
1847 (if (calc-is-inverse)
1848 (if (calc-is-hyperbolic)
1849 (calc-binary-op "lu*" 'calcFunc-lufmul arg)
1850 (calc-binary-op "lu*" 'calcFunc-lupmul arg))
1851 (if (calc-is-hyperbolic)
1852 (calc-binary-op "lu/" 'calcFunc-lufdiv arg)
1853 (calc-binary-op "lu/" 'calcFunc-lupdiv arg)))))
1855 (defun math-logunits-quant (val ref power)
1856 (let* ((units (math-simplify (math-extract-units val)))
1857 (lunit (math-simplify (math-extract-logunits units))))
1858 (if (not (eq (car-safe lunit) 'var))
1859 (calc-record-why "*Improper logarithmic unit" lunit)
1860 (let ((runits (math-simplify (math-div units lunit)))
1861 (coeff (math-simplify (math-div val units))))
1862 (math-mul
1863 (if (equal lunit '(var dB var-dB))
1864 (math-mul
1866 (math-conditional-pow
1868 (math-div
1869 coeff
1870 (if power 10 20))))
1871 (math-mul
1873 (math-conditional-apply 'calcFunc-exp
1874 (if power
1875 (math-mul 2 coeff)
1876 coeff))))
1877 runits)))))
1879 (defvar calc-lu-field-reference)
1880 (defvar calc-lu-power-reference)
1882 (defun calcFunc-lufquant (val &optional ref)
1883 (unless ref
1884 (setq ref (math-read-expr calc-lu-field-reference)))
1885 (math-logunits-quant val ref nil))
1887 (defun calcFunc-lupquant (val &optional ref)
1888 (unless ref
1889 (setq ref (math-read-expr calc-lu-power-reference)))
1890 (math-logunits-quant val ref t))
1892 (defun calc-lu-quant (arg)
1893 (interactive "P")
1894 (calc-slow-wrapper
1895 (if (calc-is-hyperbolic)
1896 (if (calc-is-option)
1897 (calc-binary-op "lupq" 'calcFunc-lufquant arg)
1898 (calc-unary-op "lupq" 'calcFunc-lufquant arg))
1899 (if (calc-is-option)
1900 (calc-binary-op "lufq" 'calcFunc-lupquant arg)
1901 (calc-unary-op "lufq" 'calcFunc-lupquant arg)))))
1903 (defun math-logunits-level (val ref db power)
1904 "Compute the value of VAL in decibels or nepers."
1905 (let* ((ratio (math-simplify-units (math-div val ref)))
1906 (ratiou (math-simplify-units (math-remove-units ratio)))
1907 (units (math-simplify (math-extract-units ratio))))
1908 (math-mul
1909 (if db
1910 (math-mul
1911 (math-mul (if power 10 20)
1912 (math-conditional-apply 'calcFunc-log10 ratiou))
1913 '(var dB var-dB))
1914 (math-mul
1915 (math-div (math-conditional-apply 'calcFunc-ln ratiou) (if power 2 1))
1916 '(var Np var-Np)))
1917 units)))
1919 (defun calcFunc-dbfield (val &optional ref)
1920 (unless ref
1921 (setq ref (math-read-expr calc-lu-field-reference)))
1922 (math-logunits-level val ref t nil))
1924 (defun calcFunc-dbpower (val &optional ref)
1925 (unless ref
1926 (setq ref (math-read-expr calc-lu-power-reference)))
1927 (math-logunits-level val ref t t))
1929 (defun calcFunc-npfield (val &optional ref)
1930 (unless ref
1931 (setq ref (math-read-expr calc-lu-field-reference)))
1932 (math-logunits-level val ref nil nil))
1934 (defun calcFunc-nppower (val &optional ref)
1935 (unless ref
1936 (setq ref (math-read-expr calc-lu-power-reference)))
1937 (math-logunits-level val ref nil t))
1939 (defun calc-db (arg)
1940 (interactive "P")
1941 (calc-slow-wrapper
1942 (if (calc-is-hyperbolic)
1943 (if (calc-is-option)
1944 (calc-binary-op "ludb" 'calcFunc-dbfield arg)
1945 (calc-unary-op "ludb" 'calcFunc-dbfield arg))
1946 (if (calc-is-option)
1947 (calc-binary-op "ludb" 'calcFunc-dbpower arg)
1948 (calc-unary-op "ludb" 'calcFunc-dbpower arg)))))
1950 (defun calc-np (arg)
1951 (interactive "P")
1952 (calc-slow-wrapper
1953 (if (calc-is-hyperbolic)
1954 (if (calc-is-option)
1955 (calc-binary-op "lunp" 'calcFunc-npfield arg)
1956 (calc-unary-op "lunp" 'calcFunc-npfield arg))
1957 (if (calc-is-option)
1958 (calc-binary-op "lunp" 'calcFunc-nppower arg)
1959 (calc-unary-op "lunp" 'calcFunc-nppower arg)))))
1961 ;;; Musical notes
1964 (defvar calc-note-threshold)
1966 (defun math-midi-round (num)
1967 "Round NUM to an integer N if NUM is within calc-note-threshold cents of N."
1968 (let* ((n (math-round num))
1969 (diff (math-abs
1970 (math-sub num n))))
1971 (if (< (math-compare diff
1972 (math-div (math-read-expr calc-note-threshold) 100)) 0)
1974 num)))
1976 (defconst math-notes
1977 '(((var C var-C) . 0)
1978 ((var Csharp var-Csharp) . 1)
1979 ; ((var C♯ var-C♯) . 1)
1980 ((var Dflat var-Dflat) . 1)
1981 ; ((var D♭ var-D♭) . 1)
1982 ((var D var-D) . 2)
1983 ((var Dsharp var-Dsharp) . 3)
1984 ; ((var D♯ var-D♯) . 3)
1985 ((var E var-E) . 4)
1986 ((var F var-F) . 5)
1987 ((var Fsharp var-Fsharp) . 6)
1988 ; ((var F♯ var-F♯) . 6)
1989 ((var Gflat var-Gflat) . 6)
1990 ; ((var G♭ var-G♭) . 6)
1991 ((var G var-G) . 7)
1992 ((var Gsharp var-Gsharp) . 8)
1993 ; ((var G♯ var-G♯) . 8)
1994 ((var A var-A) . 9)
1995 ((var Asharp var-Asharp) . 10)
1996 ; ((var A♯ var-A♯) . 10)
1997 ((var Bflat var-Bflat) . 10)
1998 ; ((var B♭ var-B♭) . 10)
1999 ((var B var-B) . 11))
2000 "An alist of notes with their number of semitones above C.")
2002 (defun math-freqp (freq)
2003 "Non-nil if FREQ is a positive number times the unit Hz.
2004 If non-nil, return the coefficient of Hz."
2005 (let ((freqcoef (math-simplify-units
2006 (math-div freq '(var Hz var-Hz)))))
2007 (if (Math-posp freqcoef) freqcoef)))
2009 (defun math-midip (num)
2010 "Non-nil if NUM is a possible MIDI note number.
2011 If non-nil, return NUM."
2012 (if (Math-numberp num) num))
2014 (defun math-spnp (spn)
2015 "Non-nil if NUM is a scientific pitch note (note + cents).
2016 If non-nil, return a list consisting of the note and the cents coefficient."
2017 (let (note cents rnote rcents)
2018 (if (eq (car-safe spn) '+)
2019 (setq note (nth 1 spn)
2020 cents (nth 2 spn))
2021 (setq note spn
2022 cents nil))
2023 (cond
2024 ((and ;; NOTE is a note, CENTS is nil or cents.
2025 (eq (car-safe note) 'calcFunc-subscr)
2026 (assoc (nth 1 note) math-notes)
2027 (integerp (nth 2 note))
2028 (setq rnote note)
2030 (not cents)
2031 (Math-numberp (setq rcents
2032 (math-simplify
2033 (math-div cents '(var cents var-cents)))))))
2034 (list rnote rcents))
2035 ((and ;; CENTS is a note, NOTE is cents.
2036 (eq (car-safe cents) 'calcFunc-subscr)
2037 (assoc (nth 1 cents) math-notes)
2038 (integerp (nth 2 cents))
2039 (setq rnote cents)
2041 (not note)
2042 (Math-numberp (setq rcents
2043 (math-simplify
2044 (math-div note '(var cents var-cents)))))))
2045 (list rnote rcents)))))
2047 (defun math-freq-to-midi (freq)
2048 "Return the midi note number corresponding to FREQ Hz."
2049 (let ((midi (math-add
2051 (math-mul
2053 (calcFunc-log
2054 (math-div freq 440)
2055 2)))))
2056 (math-midi-round midi)))
2058 (defun math-spn-to-midi (spn)
2059 "Return the MIDI number corresponding to SPN."
2060 (let* ((note (cdr (assoc (nth 1 (car spn)) math-notes)))
2061 (octave (math-add (nth 2 (car spn)) 1))
2062 (cents (nth 1 spn))
2063 (midi (math-add
2064 (math-mul 12 octave)
2065 note)))
2066 (if cents
2067 (math-add midi (math-div cents 100))
2068 midi)))
2070 (defun math-midi-to-spn (midi)
2071 "Return the scientific pitch notation corresponding to midi number MIDI."
2072 (let (midin cents)
2073 (if (math-integerp midi)
2074 (setq midin midi
2075 cents nil)
2076 (setq midin (math-floor midi)
2077 cents (math-mul 100 (math-sub midi midin))))
2078 (let* ((nr ;; This should be (math-idivmod midin 12), but with
2079 ;; better behavior for negative midin.
2080 (if (Math-negp midin)
2081 (let ((dm (math-idivmod (math-neg midin) 12)))
2082 (if (= (cdr dm) 0)
2083 (cons (math-neg (car dm)) 0)
2084 (cons
2085 (math-sub (math-neg (car dm)) 1)
2086 (math-sub 12 (cdr dm)))))
2087 (math-idivmod midin 12)))
2088 (n (math-sub (car nr) 1))
2089 (note (car (rassoc (cdr nr) math-notes))))
2090 (if cents
2091 (list '+ (list 'calcFunc-subscr note n)
2092 (list '* cents '(var cents var-cents)))
2093 (list 'calcFunc-subscr note n)))))
2095 (defun math-freq-to-spn (freq)
2096 "Return the scientific pitch notation corresponding to FREQ Hz."
2097 (math-with-extra-prec 3
2098 (math-midi-to-spn (math-freq-to-midi freq))))
2100 (defun math-midi-to-freq (midi)
2101 "Return the frequency of the note with midi number MIDI."
2102 (list '*
2103 (math-mul
2105 (math-pow
2107 (math-div
2108 (math-sub
2109 midi
2111 12)))
2112 '(var Hz var-Hz)))
2114 (defun math-spn-to-freq (spn)
2115 "Return the frequency of the note with scientific pitch notation SPN."
2116 (math-midi-to-freq (math-spn-to-midi spn)))
2118 (defun calcFunc-spn (expr)
2119 "Return EXPR written as scientific pitch notation + cents."
2120 ;; Get the coefficient of Hz
2121 (let (note)
2122 (cond
2123 ((setq note (math-freqp expr))
2124 (math-freq-to-spn note))
2125 ((setq note (math-midip expr))
2126 (math-midi-to-spn note))
2127 ((math-spnp expr)
2128 expr)
2130 (math-reject-arg expr "*Improper expression")))))
2132 (defun calcFunc-midi (expr)
2133 "Return EXPR written as a MIDI number."
2134 (let (note)
2135 (cond
2136 ((setq note (math-freqp expr))
2137 (math-freq-to-midi note))
2138 ((setq note (math-spnp expr))
2139 (math-spn-to-midi note))
2140 ((math-midip expr)
2141 expr)
2143 (math-reject-arg expr "*Improper expression")))))
2145 (defun calcFunc-freq (expr)
2146 "Return the frequency corresponding to EXPR."
2147 (let (note)
2148 (cond
2149 ((setq note (math-midip expr))
2150 (math-midi-to-freq note))
2151 ((setq note (math-spnp expr))
2152 (math-spn-to-freq note))
2153 ((math-freqp expr)
2154 expr)
2156 (math-reject-arg expr "*Improper expression")))))
2158 (defun calc-freq (arg)
2159 "Return the frequency corresponding to the expression on the stack."
2160 (interactive "P")
2161 (calc-slow-wrapper
2162 (calc-unary-op "freq" 'calcFunc-freq arg)))
2164 (defun calc-midi (arg)
2165 "Return the MIDI number corresponding to the expression on the stack."
2166 (interactive "P")
2167 (calc-slow-wrapper
2168 (calc-unary-op "midi" 'calcFunc-midi arg)))
2170 (defun calc-spn (arg)
2171 "Return the scientific pitch notation corresponding to the expression on the stack."
2172 (interactive "P")
2173 (calc-slow-wrapper
2174 (calc-unary-op "spn" 'calcFunc-spn arg)))
2177 (provide 'calc-units)
2179 ;;; calc-units.el ends here