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