]> code.delx.au - gnu-emacs/blob - lisp/calc/calc-units.el
Merge from pending; try to fix-up suboptimal ses ChangeLog.
[gnu-emacs] / lisp / calc / calc-units.el
1 ;;; calc-units.el --- unit conversion functions for Calc
2
3 ;; Copyright (C) 1990-1993, 2001-2012 Free Software Foundation, Inc.
4
5 ;; Author: David Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>
7
8 ;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 ;; This file is autoloaded from calc-ext.el.
28
29 (require 'calc-ext)
30 (require 'calc-macs)
31 (eval-when-compile
32 (require 'calc-alg))
33
34 ;;; Units operations.
35
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
39
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.
46
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) (**)" )
76
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" )
82
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
102
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" )
114
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
120
121 ;; Acceleration
122 ( ga "980665*10^(-5) m/s^2" "*\"g\" acceleration" nil
123 "9.80665 m / s^2") ;; CODATA
124
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
142
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
151
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")
172
173 ;; Power
174 ( W "J/s" "*Watt" )
175 ( hp "550 ft lbf/s" "Horsepower") ;;ESUWM
176 ( hpm "75 m kgf/s" "Metric Horsepower") ;;ESUWM
177
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 )
186
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" )
198
199 ;; Viscosity
200 ( P "(1/10) Pa s" "*Poise" )
201 ( St "10^(-4) m^2/s" "Stokes" )
202
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" )
220
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
230
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" )
239
240 ;; Amount of substance
241 ( mol nil "*Mole" )
242
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" )
252
253 ;; Solid angle
254 ( sr nil "*Steradian" )
255
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 ( mμ "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")))
302
303
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.")
309
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" )))
335
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 ) ) ) )))
341
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).")
346
347 (defvar math-units-table-buffer-valid nil)
348
349 ;;; Units commands.
350
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))))))
358
359 (defun calc-quick-units ()
360 (interactive)
361 (calc-slow-wrapper
362 (let* ((num (- last-command-event ?0))
363 (pos (if (= num 0) 10 num))
364 (units (calc-var-value 'var-Units))
365 (expr (calc-top-n 1)))
366 (unless (and (>= num 0) (<= num 9))
367 (error "Bad unit number"))
368 (unless (math-vectorp units)
369 (error "No \"quick units\" are defined"))
370 (unless (< pos (length units))
371 (error "Unit number %d not defined" pos))
372 (if (math-units-in-expr-p expr nil)
373 (calc-enter-result 1 (format "cun%d" num)
374 (math-convert-units expr (nth pos units)))
375 (calc-enter-result 1 (format "*un%d" num)
376 (math-simplify-units
377 (math-mul expr (nth pos units))))))))
378
379 (defun math-get-standard-units (expr)
380 "Return the standard units in EXPR."
381 (math-simplify-units
382 (math-extract-units
383 (math-to-standard-units expr nil))))
384
385 (defun math-get-units (expr)
386 "Return the units in EXPR."
387 (math-simplify-units
388 (math-extract-units expr)))
389
390 (defun math-make-unit-string (expr)
391 "Return EXPR in string form.
392 If EXPR is nil, return nil."
393 (if expr
394 (let ((cexpr (math-compose-expr expr 0)))
395 (replace-regexp-in-string
396 " / " "/"
397 (if (stringp cexpr)
398 cexpr
399 (math-composition-to-string cexpr))))))
400
401 (defvar math-default-units-table
402 (make-hash-table :test 'equal)
403 "A table storing previously converted units.")
404
405 (defun math-get-default-units (expr)
406 "Get default units to use when converting the units in EXPR."
407 (let* ((units (math-get-units expr))
408 (standard-units (math-get-standard-units expr))
409 (default-units (gethash
410 standard-units
411 math-default-units-table)))
412 (if (equal units (car default-units))
413 (math-make-unit-string (cadr default-units))
414 (math-make-unit-string (car default-units)))))
415
416 (defun math-put-default-units (expr)
417 "Put the units in EXPR in the default units table."
418 (let ((units (math-get-units expr)))
419 (unless (eq units 1)
420 (let* ((standard-units (math-get-standard-units expr))
421 (default-units (gethash
422 standard-units
423 math-default-units-table)))
424 (cond
425 ((not default-units)
426 (puthash standard-units (list units) math-default-units-table))
427 ((not (equal units (car default-units)))
428 (puthash standard-units
429 (list units (car default-units))
430 math-default-units-table)))))))
431
432
433 (defun calc-convert-units (&optional old-units new-units)
434 (interactive)
435 (calc-slow-wrapper
436 (let ((expr (calc-top-n 1))
437 (uoldname nil)
438 unew
439 units
440 defunits)
441 (unless (math-units-in-expr-p expr t)
442 (let ((uold (or old-units
443 (progn
444 (setq uoldname (read-string "Old units: "))
445 (if (equal uoldname "")
446 (progn
447 (setq uoldname "1")
448 1)
449 (if (string-match "\\` */" uoldname)
450 (setq uoldname (concat "1" uoldname)))
451 (math-read-expr uoldname))))))
452 (when (eq (car-safe uold) 'error)
453 (error "Bad format in units expression: %s" (nth 1 uold)))
454 (setq expr (math-mul expr uold))))
455 (unless new-units
456 (setq defunits (math-get-default-units expr))
457 (setq new-units
458 (read-string (concat
459 (if uoldname
460 (concat "Old units: "
461 uoldname
462 ", new units")
463 "New units")
464 (if defunits
465 (concat
466 " (default "
467 defunits
468 "): ")
469 ": "))))
470
471 (if (and
472 (string= new-units "")
473 defunits)
474 (setq new-units defunits)))
475 (when (string-match "\\` */" new-units)
476 (setq new-units (concat "1" new-units)))
477 (setq units (math-read-expr new-units))
478 (when (eq (car-safe units) 'error)
479 (error "Bad format in units expression: %s" (nth 2 units)))
480 (math-put-default-units units)
481 (let ((unew (math-units-in-expr-p units t))
482 (std (and (eq (car-safe units) 'var)
483 (assq (nth 1 units) math-standard-units-systems))))
484 (if std
485 (calc-enter-result 1 "cvun" (math-simplify-units
486 (math-to-standard-units expr
487 (nth 1 std))))
488 (unless unew
489 (error "No units specified"))
490 (calc-enter-result 1 "cvun"
491 (math-convert-units
492 expr units
493 (and uoldname (not (equal uoldname "1"))))))))))
494
495 (defun calc-autorange-units (arg)
496 (interactive "P")
497 (calc-wrapper
498 (calc-change-mode 'calc-autorange-units arg nil t)
499 (message (if calc-autorange-units
500 "Adjusting target unit prefix automatically"
501 "Using target units exactly"))))
502
503 (defun calc-convert-temperature (&optional old-units new-units)
504 (interactive)
505 (calc-slow-wrapper
506 (let ((expr (calc-top-n 1))
507 (uold nil)
508 (uoldname nil)
509 unew
510 defunits)
511 (setq uold (or old-units
512 (let ((units (math-single-units-in-expr-p expr)))
513 (if units
514 (if (consp units)
515 (list 'var (car units)
516 (intern (concat "var-"
517 (symbol-name
518 (car units)))))
519 (error "Not a pure temperature expression"))
520 (math-read-expr
521 (setq uoldname (read-string
522 "Old temperature units: ")))))))
523 (when (eq (car-safe uold) 'error)
524 (error "Bad format in units expression: %s" (nth 2 uold)))
525 (or (math-units-in-expr-p expr nil)
526 (setq expr (math-mul expr uold)))
527 (setq defunits (math-get-default-units expr))
528 (setq unew (or new-units
529 (read-string
530 (concat
531 (if uoldname
532 (concat "Old temperature units: "
533 uoldname
534 ", new units")
535 "New temperature units")
536 (if defunits
537 (concat " (default "
538 defunits
539 "): ")
540 ": ")))))
541 (setq unew (math-read-expr (if (string= unew "") defunits unew)))
542 (when (eq (car-safe unew) 'error)
543 (error "Bad format in units expression: %s" (nth 2 unew)))
544 (math-put-default-units unew)
545 (let ((ntemp (calc-normalize
546 (math-simplify-units
547 (math-convert-temperature expr uold unew
548 uoldname)))))
549 (if (Math-zerop ntemp)
550 (setq ntemp (list '* ntemp unew)))
551 (let ((calc-simplify-mode 'none))
552 (calc-enter-result 1 "cvtm" ntemp))))))
553
554 (defun calc-remove-units ()
555 (interactive)
556 (calc-slow-wrapper
557 (calc-enter-result 1 "rmun" (math-simplify-units
558 (math-remove-units (calc-top-n 1))))))
559
560 (defun calc-extract-units ()
561 (interactive)
562 (calc-slow-wrapper
563 (calc-enter-result 1 "rmun" (math-simplify-units
564 (math-extract-units (calc-top-n 1))))))
565
566 ;; The variables calc-num-units and calc-den-units are local to
567 ;; calc-explain-units, but are used by calc-explain-units-rec,
568 ;; which is called by calc-explain-units.
569 (defvar calc-num-units)
570 (defvar calc-den-units)
571
572 (defun calc-explain-units ()
573 (interactive)
574 (calc-wrapper
575 (let ((calc-num-units nil)
576 (calc-den-units nil))
577 (calc-explain-units-rec (calc-top-n 1) 1)
578 (and calc-den-units (string-match "^[^(].* .*[^)]$" calc-den-units)
579 (setq calc-den-units (concat "(" calc-den-units ")")))
580 (if calc-num-units
581 (if calc-den-units
582 (message "%s per %s" calc-num-units calc-den-units)
583 (message "%s" calc-num-units))
584 (if calc-den-units
585 (message "1 per %s" calc-den-units)
586 (message "No units in expression"))))))
587
588 (defun calc-explain-units-rec (expr pow)
589 (let ((u (math-check-unit-name expr))
590 pos)
591 (if (and u (not (math-zerop pow)))
592 (let ((name (or (nth 2 u) (symbol-name (car u)))))
593 (if (eq (aref name 0) ?\*)
594 (setq name (substring name 1)))
595 (if (string-match "[^a-zA-Zα-ωΑ-Ω0-9']" name)
596 (if (string-match "^[a-zA-Zα-ωΑ-Ω0-9' ()]*$" name)
597 (while (setq pos (string-match "[ ()]" name))
598 (setq name (concat (substring name 0 pos)
599 (if (eq (aref name pos) 32) "-" "")
600 (substring name (1+ pos)))))
601 (setq name (concat "(" name ")"))))
602 (or (eq (nth 1 expr) (car u))
603 (setq name (concat (nth 2 (assq (aref (symbol-name
604 (nth 1 expr)) 0)
605 math-unit-prefixes))
606 (if (and (string-match "[^a-zA-Zα-ωΑ-Ω0-9']" name)
607 (not (memq (car u) '(mHg gf))))
608 (concat "-" name)
609 (downcase name)))))
610 (cond ((or (math-equal-int pow 1)
611 (math-equal-int pow -1)))
612 ((or (math-equal-int pow 2)
613 (math-equal-int pow -2))
614 (if (equal (nth 4 u) '((m . 1)))
615 (setq name (concat "Square-" name))
616 (setq name (concat name "-squared"))))
617 ((or (math-equal-int pow 3)
618 (math-equal-int pow -3))
619 (if (equal (nth 4 u) '((m . 1)))
620 (setq name (concat "Cubic-" name))
621 (setq name (concat name "-cubed"))))
622 (t
623 (setq name (concat name "^"
624 (math-format-number (math-abs pow))))))
625 (if (math-posp pow)
626 (setq calc-num-units (if calc-num-units
627 (concat calc-num-units " " name)
628 name))
629 (setq calc-den-units (if calc-den-units
630 (concat calc-den-units " " name)
631 name))))
632 (cond ((eq (car-safe expr) '*)
633 (calc-explain-units-rec (nth 1 expr) pow)
634 (calc-explain-units-rec (nth 2 expr) pow))
635 ((eq (car-safe expr) '/)
636 (calc-explain-units-rec (nth 1 expr) pow)
637 (calc-explain-units-rec (nth 2 expr) (- pow)))
638 ((memq (car-safe expr) '(neg + -))
639 (calc-explain-units-rec (nth 1 expr) pow))
640 ((and (eq (car-safe expr) '^)
641 (math-realp (nth 2 expr)))
642 (calc-explain-units-rec (nth 1 expr)
643 (math-mul pow (nth 2 expr))))))))
644
645 (defun calc-simplify-units ()
646 (interactive)
647 (calc-slow-wrapper
648 (calc-with-default-simplification
649 (calc-enter-result 1 "smun" (math-simplify-units (calc-top-n 1))))))
650
651 (defun calc-view-units-table (n)
652 (interactive "P")
653 (and n (setq math-units-table-buffer-valid nil))
654 (let ((win (get-buffer-window "*Units Table*")))
655 (if (and win
656 math-units-table
657 math-units-table-buffer-valid)
658 (progn
659 (bury-buffer (window-buffer win))
660 (let ((curwin (selected-window)))
661 (select-window win)
662 (switch-to-buffer nil)
663 (select-window curwin)))
664 (math-build-units-table-buffer nil))))
665
666 (defun calc-enter-units-table (n)
667 (interactive "P")
668 (and n (setq math-units-table-buffer-valid nil))
669 (math-build-units-table-buffer t)
670 (message "%s" (substitute-command-keys "Type \\[calc] to return to the Calculator")))
671
672 (defun calc-define-unit (uname desc &optional disp)
673 (interactive "SDefine unit name: \nsDescription: \nP")
674 (if disp (setq disp (read-string "Display definition: ")))
675 (calc-wrapper
676 (let ((form (calc-top-n 1))
677 (unit (assq uname math-additional-units)))
678 (or unit
679 (setq math-additional-units
680 (cons (setq unit (list uname nil nil nil nil))
681 math-additional-units)
682 math-units-table nil))
683 (setcar (cdr unit) (and (not (and (eq (car-safe form) 'var)
684 (eq (nth 1 form) uname)))
685 (not (math-equal-int form 1))
686 (math-format-flat-expr form 0)))
687 (setcar (cdr (cdr unit)) (and (not (equal desc ""))
688 desc))
689 (if disp
690 (setcar (cdr (cdr (cdr (cdr unit)))) disp))))
691 (calc-invalidate-units-table))
692
693 (defun calc-undefine-unit (uname)
694 (interactive "SUndefine unit name: ")
695 (calc-wrapper
696 (let ((unit (assq uname math-additional-units)))
697 (or unit
698 (if (assq uname math-standard-units)
699 (error "\"%s\" is a predefined unit name" uname)
700 (error "Unit name \"%s\" not found" uname)))
701 (setq math-additional-units (delq unit math-additional-units)
702 math-units-table nil)))
703 (calc-invalidate-units-table))
704
705 (defun calc-invalidate-units-table ()
706 (setq math-units-table nil)
707 (let ((buf (get-buffer "*Units Table*")))
708 (and buf
709 (with-current-buffer buf
710 (save-excursion
711 (goto-char (point-min))
712 (if (looking-at "Calculator Units Table")
713 (let ((inhibit-read-only t))
714 (insert "(Obsolete) "))))))))
715
716 (defun calc-get-unit-definition (uname)
717 (interactive "SGet definition for unit: ")
718 (calc-wrapper
719 (math-build-units-table)
720 (let ((unit (assq uname math-units-table)))
721 (or unit
722 (error "Unit name \"%s\" not found" uname))
723 (let ((msg (nth 2 unit)))
724 (if (stringp msg)
725 (if (string-match "^\\*" msg)
726 (setq msg (substring msg 1)))
727 (setq msg (symbol-name uname)))
728 (if (nth 1 unit)
729 (progn
730 (calc-enter-result 0 "ugdf" (nth 1 unit))
731 (message "Derived unit: %s" msg))
732 (calc-enter-result 0 "ugdf" (list 'var uname
733 (intern
734 (concat "var-"
735 (symbol-name uname)))))
736 (message "Base unit: %s" msg))))))
737
738 (defun calc-permanent-units ()
739 (interactive)
740 (calc-wrapper
741 (let (pos)
742 (set-buffer (find-file-noselect (substitute-in-file-name
743 calc-settings-file)))
744 (goto-char (point-min))
745 (if (and (search-forward ";;; Custom units stored by Calc" nil t)
746 (progn
747 (beginning-of-line)
748 (setq pos (point))
749 (search-forward "\n;;; End of custom units" nil t)))
750 (progn
751 (beginning-of-line)
752 (forward-line 1)
753 (delete-region pos (point)))
754 (goto-char (point-max))
755 (insert "\n\n")
756 (forward-char -1))
757 (insert ";;; Custom units stored by Calc on " (current-time-string) "\n")
758 (if math-additional-units
759 (progn
760 (insert "(setq math-additional-units '(\n")
761 (let ((list math-additional-units))
762 (while list
763 (insert " (" (symbol-name (car (car list))) " "
764 (if (nth 1 (car list))
765 (if (stringp (nth 1 (car list)))
766 (prin1-to-string (nth 1 (car list)))
767 (prin1-to-string (math-format-flat-expr
768 (nth 1 (car list)) 0)))
769 "nil")
770 " "
771 (prin1-to-string (nth 2 (car list)))
772 ")\n")
773 (setq list (cdr list))))
774 (insert "))\n"))
775 (insert ";;; (no custom units defined)\n"))
776 (insert ";;; End of custom units\n")
777 (save-buffer))))
778
779
780 ;; The variable math-cu-unit-list is local to math-build-units-table,
781 ;; but is used by math-compare-unit-names, which is called (indirectly)
782 ;; by math-build-units-table.
783 ;; math-cu-unit-list is also local to math-convert-units, but is used
784 ;; by math-convert-units-rec, which is called by math-convert-units.
785 (defvar math-cu-unit-list)
786
787 (defun math-build-units-table ()
788 (or math-units-table
789 (let* ((combined-units (append math-additional-units
790 math-standard-units))
791 (math-cu-unit-list (mapcar 'car combined-units))
792 tab)
793 (message "Building units table...")
794 (setq math-units-table-buffer-valid nil)
795 (setq tab (mapcar (function
796 (lambda (x)
797 (list (car x)
798 (and (nth 1 x)
799 (if (stringp (nth 1 x))
800 (let ((exp (math-read-plain-expr
801 (nth 1 x))))
802 (if (eq (car-safe exp) 'error)
803 (error "Format error in definition of %s in units table: %s"
804 (car x) (nth 2 exp))
805 exp))
806 (nth 1 x)))
807 (nth 2 x)
808 (nth 3 x)
809 (and (not (nth 1 x))
810 (list (cons (car x) 1)))
811 (nth 4 x))))
812 combined-units))
813 (let ((math-units-table tab))
814 (mapc 'math-find-base-units tab))
815 (message "Building units table...done")
816 (setq math-units-table tab))))
817
818 ;; The variables math-fbu-base and math-fbu-entry are local to
819 ;; math-find-base-units, but are used by math-find-base-units-rec,
820 ;; which is called by math-find-base-units.
821 (defvar math-fbu-base)
822 (defvar math-fbu-entry)
823
824 (defun math-find-base-units (math-fbu-entry)
825 (if (eq (nth 4 math-fbu-entry) 'boom)
826 (error "Circular definition involving unit %s" (car math-fbu-entry)))
827 (or (nth 4 math-fbu-entry)
828 (let (math-fbu-base)
829 (setcar (nthcdr 4 math-fbu-entry) 'boom)
830 (math-find-base-units-rec (nth 1 math-fbu-entry) 1)
831 '(or math-fbu-base
832 (error "Dimensionless definition for unit %s" (car math-fbu-entry)))
833 (while (eq (cdr (car math-fbu-base)) 0)
834 (setq math-fbu-base (cdr math-fbu-base)))
835 (let ((b math-fbu-base))
836 (while (cdr b)
837 (if (eq (cdr (car (cdr b))) 0)
838 (setcdr b (cdr (cdr b)))
839 (setq b (cdr b)))))
840 (setq math-fbu-base (sort math-fbu-base 'math-compare-unit-names))
841 (setcar (nthcdr 4 math-fbu-entry) math-fbu-base)
842 math-fbu-base)))
843
844 (defun math-compare-unit-names (a b)
845 (memq (car b) (cdr (memq (car a) math-cu-unit-list))))
846
847 (defun math-find-base-units-rec (expr pow)
848 (let ((u (math-check-unit-name expr)))
849 (cond (u
850 (let ((ulist (math-find-base-units u)))
851 (while ulist
852 (let ((p (* (cdr (car ulist)) pow))
853 (old (assq (car (car ulist)) math-fbu-base)))
854 (if old
855 (setcdr old (+ (cdr old) p))
856 (setq math-fbu-base
857 (cons (cons (car (car ulist)) p) math-fbu-base))))
858 (setq ulist (cdr ulist)))))
859 ((math-scalarp expr))
860 ((and (eq (car expr) '^)
861 (integerp (nth 2 expr)))
862 (math-find-base-units-rec (nth 1 expr) (* pow (nth 2 expr))))
863 ((eq (car expr) '*)
864 (math-find-base-units-rec (nth 1 expr) pow)
865 (math-find-base-units-rec (nth 2 expr) pow))
866 ((eq (car expr) '/)
867 (math-find-base-units-rec (nth 1 expr) pow)
868 (math-find-base-units-rec (nth 2 expr) (- pow)))
869 ((eq (car expr) 'neg)
870 (math-find-base-units-rec (nth 1 expr) pow))
871 ((eq (car expr) '+)
872 (math-find-base-units-rec (nth 1 expr) pow))
873 ((eq (car expr) 'var)
874 (or (eq (nth 1 expr) 'pi)
875 (error "Unknown name %s in defining expression for unit %s"
876 (nth 1 expr) (car math-fbu-entry))))
877 ((equal expr '(calcFunc-ln 10)))
878 (t (error "Malformed defining expression for unit %s" (car math-fbu-entry))))))
879
880
881 (defun math-units-in-expr-p (expr sub-exprs)
882 (and (consp expr)
883 (if (eq (car expr) 'var)
884 (math-check-unit-name expr)
885 (and (or sub-exprs
886 (memq (car expr) '(* / ^)))
887 (or (math-units-in-expr-p (nth 1 expr) sub-exprs)
888 (math-units-in-expr-p (nth 2 expr) sub-exprs))))))
889
890 (defun math-only-units-in-expr-p (expr)
891 (and (consp expr)
892 (if (eq (car expr) 'var)
893 (math-check-unit-name expr)
894 (if (memq (car expr) '(* /))
895 (and (math-only-units-in-expr-p (nth 1 expr))
896 (math-only-units-in-expr-p (nth 2 expr)))
897 (and (eq (car expr) '^)
898 (and (math-only-units-in-expr-p (nth 1 expr))
899 (math-realp (nth 2 expr))))))))
900
901 (defun math-single-units-in-expr-p (expr)
902 (cond ((math-scalarp expr) nil)
903 ((eq (car expr) 'var)
904 (math-check-unit-name expr))
905 ((eq (car expr) '*)
906 (let ((u1 (math-single-units-in-expr-p (nth 1 expr)))
907 (u2 (math-single-units-in-expr-p (nth 2 expr))))
908 (or (and u1 u2 'wrong)
909 u1
910 u2)))
911 ((eq (car expr) '/)
912 (if (math-units-in-expr-p (nth 2 expr) nil)
913 'wrong
914 (math-single-units-in-expr-p (nth 1 expr))))
915 (t 'wrong)))
916
917 (defun math-check-unit-name (v)
918 (and (eq (car-safe v) 'var)
919 (or (assq (nth 1 v) (or math-units-table (math-build-units-table)))
920 (let ((name (symbol-name (nth 1 v))))
921 (and (> (length name) 1)
922 (assq (aref name 0) math-unit-prefixes)
923 (or (assq (intern (substring name 1)) math-units-table)
924 (and (eq (aref name 0) ?M)
925 (> (length name) 3)
926 (eq (aref name 1) ?e)
927 (eq (aref name 2) ?g)
928 (assq (intern (substring name 3))
929 math-units-table))))))))
930
931 ;; The variable math-which-standard is local to math-to-standard-units,
932 ;; but is used by math-to-standard-rec, which is called by
933 ;; math-to-standard-units.
934 (defvar math-which-standard)
935
936 (defun math-to-standard-units (expr math-which-standard)
937 (math-to-standard-rec expr))
938
939 (defun math-to-standard-rec (expr)
940 (if (eq (car-safe expr) 'var)
941 (let ((u (math-check-unit-name expr))
942 (base (nth 1 expr)))
943 (if u
944 (progn
945 (if (nth 1 u)
946 (setq expr (math-to-standard-rec (nth 1 u)))
947 (let ((st (assq (car u) math-which-standard)))
948 (if st
949 (setq expr (nth 1 st))
950 (setq expr (list 'var (car u)
951 (intern (concat "var-"
952 (symbol-name
953 (car u)))))))))
954 (or (null u)
955 (eq base (car u))
956 (setq expr (list '*
957 (nth 1 (assq (aref (symbol-name base) 0)
958 math-unit-prefixes))
959 expr)))
960 expr)
961 (if (eq base 'pi)
962 (math-pi)
963 expr)))
964 (if (or
965 (Math-primp expr)
966 (and (eq (car-safe expr) 'calcFunc-subscr)
967 (eq (car-safe (nth 1 expr)) 'var)))
968 expr
969 (cons (car expr)
970 (mapcar 'math-to-standard-rec (cdr expr))))))
971
972 (defun math-apply-units (expr units ulist &optional pure)
973 (setq expr (math-simplify-units expr))
974 (if ulist
975 (let ((new 0)
976 value)
977 (or (math-numberp expr)
978 (error "Incompatible units"))
979 (while (cdr ulist)
980 (setq value (math-div expr (nth 1 (car ulist)))
981 value (math-floor (let ((calc-internal-prec
982 (1- calc-internal-prec)))
983 (math-normalize value)))
984 new (math-add new (math-mul value (car (car ulist))))
985 expr (math-sub expr (math-mul value (nth 1 (car ulist))))
986 ulist (cdr ulist)))
987 (math-add new (math-mul (math-div expr (nth 1 (car ulist)))
988 (car (car ulist)))))
989 (if pure
990 expr
991 (math-simplify-units (list '* expr units)))))
992
993 (defvar math-decompose-units-cache nil)
994 (defun math-decompose-units (units)
995 (let ((u (math-check-unit-name units)))
996 (and u (eq (car-safe (nth 1 u)) '+)
997 (setq units (nth 1 u))))
998 (setq units (calcFunc-expand units))
999 (and (eq (car-safe units) '+)
1000 (let ((entry (list units calc-internal-prec calc-prefer-frac)))
1001 (or (equal entry (car math-decompose-units-cache))
1002 (let ((ulist nil)
1003 (utemp units)
1004 qty unit)
1005 (while (eq (car-safe utemp) '+)
1006 (setq ulist (cons (math-decompose-unit-part (nth 2 utemp))
1007 ulist)
1008 utemp (nth 1 utemp)))
1009 (setq ulist (cons (math-decompose-unit-part utemp) ulist)
1010 utemp ulist)
1011 (while (setq utemp (cdr utemp))
1012 (unless (equal (nth 2 (car utemp)) (nth 2 (car ulist)))
1013 (error "Inconsistent units in sum")))
1014 (setq math-decompose-units-cache
1015 (cons entry
1016 (sort ulist
1017 (function
1018 (lambda (x y)
1019 (not (Math-lessp (nth 1 x)
1020 (nth 1 y))))))))))
1021 (cdr math-decompose-units-cache))))
1022
1023 (defun math-decompose-unit-part (unit)
1024 (cons unit
1025 (math-is-multiple (math-simplify-units (math-to-standard-units
1026 unit nil))
1027 t)))
1028
1029 ;; The variable math-fcu-u is local to math-find-compatible-unit,
1030 ;; but is used by math-find-compatible-rec which is called by
1031 ;; math-find-compatible-unit.
1032 (defvar math-fcu-u)
1033
1034 (defun math-find-compatible-unit (expr unit)
1035 (let ((math-fcu-u (math-check-unit-name unit)))
1036 (if math-fcu-u
1037 (math-find-compatible-unit-rec expr 1))))
1038
1039 (defun math-find-compatible-unit-rec (expr pow)
1040 (cond ((eq (car-safe expr) '*)
1041 (or (math-find-compatible-unit-rec (nth 1 expr) pow)
1042 (math-find-compatible-unit-rec (nth 2 expr) pow)))
1043 ((eq (car-safe expr) '/)
1044 (or (math-find-compatible-unit-rec (nth 1 expr) pow)
1045 (math-find-compatible-unit-rec (nth 2 expr) (- pow))))
1046 ((and (eq (car-safe expr) '^)
1047 (integerp (nth 2 expr)))
1048 (math-find-compatible-unit-rec (nth 1 expr) (* pow (nth 2 expr))))
1049 (t
1050 (let ((u2 (math-check-unit-name expr)))
1051 (if (equal (nth 4 math-fcu-u) (nth 4 u2))
1052 (cons expr pow))))))
1053
1054 ;; The variables math-cu-new-units and math-cu-pure are local to
1055 ;; math-convert-units, but are used by math-convert-units-rec,
1056 ;; which is called by math-convert-units.
1057 (defvar math-cu-new-units)
1058 (defvar math-cu-pure)
1059
1060 (defun math-convert-units (expr math-cu-new-units &optional math-cu-pure)
1061 (if (eq (car-safe math-cu-new-units) 'var)
1062 (let ((unew (assq (nth 1 math-cu-new-units)
1063 (math-build-units-table))))
1064 (if (eq (car-safe (nth 1 unew)) '+)
1065 (setq math-cu-new-units (nth 1 unew)))))
1066 (math-with-extra-prec 2
1067 (let ((compat (and (not math-cu-pure)
1068 (math-find-compatible-unit expr math-cu-new-units)))
1069 (math-cu-unit-list nil)
1070 (math-combining-units nil))
1071 (if compat
1072 (math-simplify-units
1073 (math-mul (math-mul (math-simplify-units
1074 (math-div expr (math-pow (car compat)
1075 (cdr compat))))
1076 (math-pow math-cu-new-units (cdr compat)))
1077 (math-simplify-units
1078 (math-to-standard-units
1079 (math-pow (math-div (car compat) math-cu-new-units)
1080 (cdr compat))
1081 nil))))
1082 (when (setq math-cu-unit-list (math-decompose-units math-cu-new-units))
1083 (setq math-cu-new-units (nth 2 (car math-cu-unit-list))))
1084 (when (eq (car-safe expr) '+)
1085 (setq expr (math-simplify-units expr)))
1086 (if (math-units-in-expr-p expr t)
1087 (math-convert-units-rec expr)
1088 (math-apply-units (math-to-standard-units
1089 (list '/ expr math-cu-new-units) nil)
1090 math-cu-new-units math-cu-unit-list math-cu-pure))))))
1091
1092 (defun math-convert-units-rec (expr)
1093 (if (math-units-in-expr-p expr nil)
1094 (math-apply-units (math-to-standard-units
1095 (list '/ expr math-cu-new-units) nil)
1096 math-cu-new-units math-cu-unit-list math-cu-pure)
1097 (if (Math-primp expr)
1098 expr
1099 (cons (car expr)
1100 (mapcar 'math-convert-units-rec (cdr expr))))))
1101
1102 (defun math-convert-temperature (expr old new &optional pure)
1103 (let* ((units (math-single-units-in-expr-p expr))
1104 (uold (if old
1105 (if (or (null units)
1106 (equal (nth 1 old) (car units)))
1107 (math-check-unit-name old)
1108 (error "Inconsistent temperature units"))
1109 units))
1110 (unew (math-check-unit-name new)))
1111 (unless (and (consp unew) (nth 3 unew))
1112 (error "Not a valid temperature unit"))
1113 (unless (and (consp uold) (nth 3 uold))
1114 (error "Not a pure temperature expression"))
1115 (let ((v (car uold)))
1116 (setq expr (list '/ expr (list 'var v
1117 (intern (concat "var-"
1118 (symbol-name v)))))))
1119 (or (eq (nth 3 uold) (nth 3 unew))
1120 (cond ((eq (nth 3 uold) 'K)
1121 (setq expr (list '- expr '(/ 27315 100)))
1122 (if (eq (nth 3 unew) 'F)
1123 (setq expr (list '+ (list '* expr '(/ 9 5)) 32))))
1124 ((eq (nth 3 uold) 'C)
1125 (if (eq (nth 3 unew) 'F)
1126 (setq expr (list '+ (list '* expr '(/ 9 5)) 32))
1127 (setq expr (list '+ expr '(/ 27315 100)))))
1128 (t
1129 (setq expr (list '* (list '- expr 32) '(/ 5 9)))
1130 (if (eq (nth 3 unew) 'K)
1131 (setq expr (list '+ expr '(/ 27315 100)))))))
1132 (if pure
1133 expr
1134 (list '* expr new))))
1135
1136
1137
1138 (defun math-simplify-units (a)
1139 (let ((math-simplifying-units t)
1140 (calc-matrix-mode 'scalar))
1141 (math-simplify a)))
1142 (defalias 'calcFunc-usimplify 'math-simplify-units)
1143
1144 ;; The function created by math-defsimplify uses the variable
1145 ;; math-simplify-expr, and so is used by functions in math-defsimplify
1146 (defvar math-simplify-expr)
1147
1148 (math-defsimplify (+ -)
1149 (and math-simplifying-units
1150 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1151 (let* ((units (math-extract-units (nth 1 math-simplify-expr)))
1152 (ratio (math-simplify (math-to-standard-units
1153 (list '/ (nth 2 math-simplify-expr) units) nil))))
1154 (if (math-units-in-expr-p ratio nil)
1155 (progn
1156 (calc-record-why "*Inconsistent units" math-simplify-expr)
1157 math-simplify-expr)
1158 (list '* (math-add (math-remove-units (nth 1 math-simplify-expr))
1159 (if (eq (car math-simplify-expr) '-)
1160 (math-neg ratio) ratio))
1161 units)))))
1162
1163 (math-defsimplify *
1164 (math-simplify-units-prod))
1165
1166 (defun math-simplify-units-prod ()
1167 (and math-simplifying-units
1168 calc-autorange-units
1169 (Math-realp (nth 1 math-simplify-expr))
1170 (let* ((num (math-float (nth 1 math-simplify-expr)))
1171 (xpon (calcFunc-xpon num))
1172 (unitp (cdr (cdr math-simplify-expr)))
1173 (unit (car unitp))
1174 (pow (if (eq (car math-simplify-expr) '*) 1 -1))
1175 u)
1176 (and (eq (car-safe unit) '*)
1177 (setq unitp (cdr unit)
1178 unit (car unitp)))
1179 (and (eq (car-safe unit) '^)
1180 (integerp (nth 2 unit))
1181 (setq pow (* pow (nth 2 unit))
1182 unitp (cdr unit)
1183 unit (car unitp)))
1184 (and (setq u (math-check-unit-name unit))
1185 (integerp xpon)
1186 (or (< xpon 0)
1187 (>= xpon (if (eq (car u) 'm) 1 3)))
1188 (let* ((uxpon 0)
1189 (pref (if (< pow 0)
1190 (reverse math-unit-prefixes)
1191 math-unit-prefixes))
1192 (p pref)
1193 pxpon pname)
1194 (or (eq (car u) (nth 1 unit))
1195 (setq uxpon (* pow
1196 (nth 2 (nth 1 (assq
1197 (aref (symbol-name
1198 (nth 1 unit)) 0)
1199 math-unit-prefixes))))))
1200 (setq xpon (+ xpon uxpon))
1201 (while (and p
1202 (or (memq (car (car p)) '(?d ?D ?h ?H))
1203 (and (eq (car (car p)) ?c)
1204 (not (eq (car u) 'm)))
1205 (< xpon (setq pxpon (* (nth 2 (nth 1 (car p)))
1206 pow)))
1207 (progn
1208 (setq pname (math-build-var-name
1209 (if (eq (car (car p)) 0)
1210 (car u)
1211 (concat (char-to-string
1212 (car (car p)))
1213 (symbol-name
1214 (car u))))))
1215 (and (/= (car (car p)) 0)
1216 (assq (nth 1 pname)
1217 math-units-table)))))
1218 (setq p (cdr p)))
1219 (and p
1220 (/= pxpon uxpon)
1221 (or (not (eq p pref))
1222 (< xpon (+ pxpon (* (math-abs pow) 3))))
1223 (progn
1224 (setcar (cdr math-simplify-expr)
1225 (let ((calc-prefer-frac nil))
1226 (calcFunc-scf (nth 1 math-simplify-expr)
1227 (- uxpon pxpon))))
1228 (setcar unitp pname)
1229 math-simplify-expr)))))))
1230
1231 (defvar math-try-cancel-units)
1232
1233 (math-defsimplify /
1234 (and math-simplifying-units
1235 (let ((np (cdr math-simplify-expr))
1236 (math-try-cancel-units 0)
1237 n nn)
1238 (setq n (if (eq (car-safe (nth 2 math-simplify-expr)) '*)
1239 (cdr (nth 2 math-simplify-expr))
1240 (nthcdr 2 math-simplify-expr)))
1241 (if (math-realp (car n))
1242 (progn
1243 (setcar (cdr math-simplify-expr) (math-mul (nth 1 math-simplify-expr)
1244 (let ((calc-prefer-frac nil))
1245 (math-div 1 (car n)))))
1246 (setcar n 1)))
1247 (while (eq (car-safe (setq n (car np))) '*)
1248 (math-simplify-units-divisor (cdr n) (cdr (cdr math-simplify-expr)))
1249 (setq np (cdr (cdr n))))
1250 (math-simplify-units-divisor np (cdr (cdr math-simplify-expr)))
1251 (if (eq math-try-cancel-units 0)
1252 (let* ((math-simplifying-units nil)
1253 (base (math-simplify
1254 (math-to-standard-units math-simplify-expr nil))))
1255 (if (Math-numberp base)
1256 (setq math-simplify-expr base))))
1257 (if (eq (car-safe math-simplify-expr) '/)
1258 (math-simplify-units-prod))
1259 math-simplify-expr)))
1260
1261 (defun math-simplify-units-divisor (np dp)
1262 (let ((n (car np))
1263 d dd temp)
1264 (while (eq (car-safe (setq d (car dp))) '*)
1265 (when (setq temp (math-simplify-units-quotient n (nth 1 d)))
1266 (setcar np (setq n temp))
1267 (setcar (cdr d) 1))
1268 (setq dp (cdr (cdr d))))
1269 (when (setq temp (math-simplify-units-quotient n d))
1270 (setcar np (setq n temp))
1271 (setcar dp 1))))
1272
1273 ;; Simplify, e.g., "in / cm" to "2.54" in a units expression.
1274 (defun math-simplify-units-quotient (n d)
1275 (let ((pow1 1)
1276 (pow2 1))
1277 (when (and (eq (car-safe n) '^)
1278 (integerp (nth 2 n)))
1279 (setq pow1 (nth 2 n) n (nth 1 n)))
1280 (when (and (eq (car-safe d) '^)
1281 (integerp (nth 2 d)))
1282 (setq pow2 (nth 2 d) d (nth 1 d)))
1283 (let ((un (math-check-unit-name n))
1284 (ud (math-check-unit-name d)))
1285 (and un ud
1286 (if (and (equal (nth 4 un) (nth 4 ud))
1287 (eq pow1 pow2))
1288 (if (eq pow1 1)
1289 (math-to-standard-units (list '/ n d) nil)
1290 (list '^ (math-to-standard-units (list '/ n d) nil) pow1))
1291 (let (ud1)
1292 (setq un (nth 4 un)
1293 ud (nth 4 ud))
1294 (while un
1295 (setq ud1 ud)
1296 (while ud1
1297 (and (eq (car (car un)) (car (car ud1)))
1298 (setq math-try-cancel-units
1299 (+ math-try-cancel-units
1300 (- (* (cdr (car un)) pow1)
1301 (* (cdr (car ud)) pow2)))))
1302 (setq ud1 (cdr ud1)))
1303 (setq un (cdr un)))
1304 nil))))))
1305
1306 (math-defsimplify ^
1307 (and math-simplifying-units
1308 (math-realp (nth 2 math-simplify-expr))
1309 (if (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1310 (list (car (nth 1 math-simplify-expr))
1311 (list '^ (nth 1 (nth 1 math-simplify-expr))
1312 (nth 2 math-simplify-expr))
1313 (list '^ (nth 2 (nth 1 math-simplify-expr))
1314 (nth 2 math-simplify-expr)))
1315 (math-simplify-units-pow (nth 1 math-simplify-expr)
1316 (nth 2 math-simplify-expr)))))
1317
1318 (math-defsimplify calcFunc-sqrt
1319 (and math-simplifying-units
1320 (if (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1321 (list (car (nth 1 math-simplify-expr))
1322 (list 'calcFunc-sqrt (nth 1 (nth 1 math-simplify-expr)))
1323 (list 'calcFunc-sqrt (nth 2 (nth 1 math-simplify-expr))))
1324 (math-simplify-units-pow (nth 1 math-simplify-expr) '(frac 1 2)))))
1325
1326 (math-defsimplify (calcFunc-floor
1327 calcFunc-ceil
1328 calcFunc-round
1329 calcFunc-rounde
1330 calcFunc-roundu
1331 calcFunc-trunc
1332 calcFunc-float
1333 calcFunc-frac
1334 calcFunc-abs
1335 calcFunc-clean)
1336 (and math-simplifying-units
1337 (= (length math-simplify-expr) 2)
1338 (if (math-only-units-in-expr-p (nth 1 math-simplify-expr))
1339 (nth 1 math-simplify-expr)
1340 (if (and (memq (car-safe (nth 1 math-simplify-expr)) '(* /))
1341 (or (math-only-units-in-expr-p
1342 (nth 1 (nth 1 math-simplify-expr)))
1343 (math-only-units-in-expr-p
1344 (nth 2 (nth 1 math-simplify-expr)))))
1345 (list (car (nth 1 math-simplify-expr))
1346 (cons (car math-simplify-expr)
1347 (cons (nth 1 (nth 1 math-simplify-expr))
1348 (cdr (cdr math-simplify-expr))))
1349 (cons (car math-simplify-expr)
1350 (cons (nth 2 (nth 1 math-simplify-expr))
1351 (cdr (cdr math-simplify-expr)))))))))
1352
1353 (defun math-simplify-units-pow (a pow)
1354 (if (and (eq (car-safe a) '^)
1355 (math-check-unit-name (nth 1 a))
1356 (math-realp (nth 2 a)))
1357 (list '^ (nth 1 a) (math-mul pow (nth 2 a)))
1358 (let* ((u (math-check-unit-name a))
1359 (pf (math-to-simple-fraction pow))
1360 (d (and (eq (car-safe pf) 'frac) (nth 2 pf))))
1361 (and u d
1362 (math-units-are-multiple u d)
1363 (list '^ (math-to-standard-units a nil) pow)))))
1364
1365
1366 (defun math-units-are-multiple (u n)
1367 (setq u (nth 4 u))
1368 (while (and u (= (% (cdr (car u)) n) 0))
1369 (setq u (cdr u)))
1370 (null u))
1371
1372 (math-defsimplify calcFunc-sin
1373 (and math-simplifying-units
1374 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1375 (let ((rad (math-simplify-units
1376 (math-evaluate-expr
1377 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1378 (calc-angle-mode 'rad))
1379 (and (eq (car-safe rad) '*)
1380 (math-realp (nth 1 rad))
1381 (eq (car-safe (nth 2 rad)) 'var)
1382 (eq (nth 1 (nth 2 rad)) 'rad)
1383 (list 'calcFunc-sin (nth 1 rad))))))
1384
1385 (math-defsimplify calcFunc-cos
1386 (and math-simplifying-units
1387 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1388 (let ((rad (math-simplify-units
1389 (math-evaluate-expr
1390 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1391 (calc-angle-mode 'rad))
1392 (and (eq (car-safe rad) '*)
1393 (math-realp (nth 1 rad))
1394 (eq (car-safe (nth 2 rad)) 'var)
1395 (eq (nth 1 (nth 2 rad)) 'rad)
1396 (list 'calcFunc-cos (nth 1 rad))))))
1397
1398 (math-defsimplify calcFunc-tan
1399 (and math-simplifying-units
1400 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1401 (let ((rad (math-simplify-units
1402 (math-evaluate-expr
1403 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1404 (calc-angle-mode 'rad))
1405 (and (eq (car-safe rad) '*)
1406 (math-realp (nth 1 rad))
1407 (eq (car-safe (nth 2 rad)) 'var)
1408 (eq (nth 1 (nth 2 rad)) 'rad)
1409 (list 'calcFunc-tan (nth 1 rad))))))
1410
1411 (math-defsimplify calcFunc-sec
1412 (and math-simplifying-units
1413 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1414 (let ((rad (math-simplify-units
1415 (math-evaluate-expr
1416 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1417 (calc-angle-mode 'rad))
1418 (and (eq (car-safe rad) '*)
1419 (math-realp (nth 1 rad))
1420 (eq (car-safe (nth 2 rad)) 'var)
1421 (eq (nth 1 (nth 2 rad)) 'rad)
1422 (list 'calcFunc-sec (nth 1 rad))))))
1423
1424 (math-defsimplify calcFunc-csc
1425 (and math-simplifying-units
1426 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1427 (let ((rad (math-simplify-units
1428 (math-evaluate-expr
1429 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1430 (calc-angle-mode 'rad))
1431 (and (eq (car-safe rad) '*)
1432 (math-realp (nth 1 rad))
1433 (eq (car-safe (nth 2 rad)) 'var)
1434 (eq (nth 1 (nth 2 rad)) 'rad)
1435 (list 'calcFunc-csc (nth 1 rad))))))
1436
1437 (math-defsimplify calcFunc-cot
1438 (and math-simplifying-units
1439 (math-units-in-expr-p (nth 1 math-simplify-expr) nil)
1440 (let ((rad (math-simplify-units
1441 (math-evaluate-expr
1442 (math-to-standard-units (nth 1 math-simplify-expr) nil))))
1443 (calc-angle-mode 'rad))
1444 (and (eq (car-safe rad) '*)
1445 (math-realp (nth 1 rad))
1446 (eq (car-safe (nth 2 rad)) 'var)
1447 (eq (nth 1 (nth 2 rad)) 'rad)
1448 (list 'calcFunc-cot (nth 1 rad))))))
1449
1450
1451 (defun math-remove-units (expr)
1452 (if (math-check-unit-name expr)
1453 1
1454 (if (Math-primp expr)
1455 expr
1456 (cons (car expr)
1457 (mapcar 'math-remove-units (cdr expr))))))
1458
1459 (defun math-extract-units (expr)
1460 (if (memq (car-safe expr) '(* /))
1461 (cons (car expr)
1462 (mapcar 'math-extract-units (cdr expr)))
1463 (if (math-check-unit-name expr) expr 1)))
1464
1465 (defun math-build-units-table-buffer (enter-buffer)
1466 (if (not (and math-units-table math-units-table-buffer-valid
1467 (get-buffer "*Units Table*")))
1468 (let ((buf (get-buffer-create "*Units Table*"))
1469 (uptr (math-build-units-table))
1470 (calc-language (if (eq calc-language 'big) nil calc-language))
1471 (calc-float-format '(float 0))
1472 (calc-group-digits nil)
1473 (calc-number-radix 10)
1474 (calc-twos-complement-mode nil)
1475 (calc-point-char ".")
1476 (std nil)
1477 u name shadowed)
1478 (save-excursion
1479 (message "Formatting units table...")
1480 (set-buffer buf)
1481 (let ((inhibit-read-only t))
1482 (erase-buffer)
1483 (insert "Calculator Units Table:\n\n")
1484 (insert "(All definitions are exact unless marked with an asterisk (*).)\n\n")
1485 (insert "Unit Type Definition Description\n\n")
1486 (while uptr
1487 (setq u (car uptr)
1488 name (nth 2 u))
1489 (when (eq (car u) 'm)
1490 (setq std t))
1491 (setq shadowed (and std (assq (car u) math-additional-units)))
1492 (when (and name
1493 (> (length name) 1)
1494 (eq (aref name 0) ?\*))
1495 (unless (eq uptr math-units-table)
1496 (insert "\n"))
1497 (setq name (substring name 1)))
1498 (insert " ")
1499 (and shadowed (insert "("))
1500 (insert (symbol-name (car u)))
1501 (and shadowed (insert ")"))
1502 (if (nth 3 u)
1503 (progn
1504 (indent-to 10)
1505 (insert (symbol-name (nth 3 u))))
1506 (or std
1507 (progn
1508 (indent-to 10)
1509 (insert "U"))))
1510 (indent-to 14)
1511 (and shadowed (insert "("))
1512 (if (nth 5 u)
1513 (insert (nth 5 u))
1514 (if (nth 1 u)
1515 (insert (math-format-value (nth 1 u) 80))
1516 (insert (symbol-name (car u)))))
1517 (and shadowed (insert ")"))
1518 (indent-to 41)
1519 (insert " ")
1520 (when name
1521 (insert name))
1522 (if shadowed
1523 (insert " (redefined above)")
1524 (unless (nth 1 u)
1525 (insert " (base unit)")))
1526 (insert "\n")
1527 (setq uptr (cdr uptr)))
1528 (insert "\n\nUnit Prefix Table:\n\n")
1529 (setq uptr math-unit-prefixes)
1530 (while uptr
1531 (setq u (car uptr))
1532 (insert " " (char-to-string (car u)))
1533 (if (equal (nth 1 u) (nth 1 (nth 1 uptr)))
1534 (insert " " (char-to-string (car (car (setq uptr (cdr uptr)))))
1535 " ")
1536 (insert " "))
1537 (insert "10^" (int-to-string (nth 2 (nth 1 u))))
1538 (indent-to 15)
1539 (insert " " (nth 2 u) "\n")
1540 (while (eq (car (car (setq uptr (cdr uptr)))) 0)))
1541 (insert "\n\n")
1542 (insert "(**) When in TeX or LaTeX display mode, the TeX specific unit\n"
1543 "names will not use the `tex' prefix; the unit name for a\n"
1544 "TeX point will be `pt' instead of `texpt', for example.\n"
1545 "To avoid conflicts, the unit names for pint and parsec will\n"
1546 "be `pint' and `parsec' instead of `pt' and `pc'."))
1547 (view-mode)
1548 (message "Formatting units table...done"))
1549 (setq math-units-table-buffer-valid t)
1550 (let ((oldbuf (current-buffer)))
1551 (set-buffer buf)
1552 (goto-char (point-min))
1553 (set-buffer oldbuf))
1554 (if enter-buffer
1555 (pop-to-buffer buf)
1556 (display-buffer buf)))
1557 (if enter-buffer
1558 (pop-to-buffer (get-buffer "*Units Table*"))
1559 (display-buffer (get-buffer "*Units Table*")))))
1560
1561 ;;; Logarithmic units functions
1562
1563 (defvar math-logunits '((var dB var-dB)
1564 (var Np var-Np)))
1565
1566 (defun math-conditional-apply (fn &rest args)
1567 "Evaluate f(args) unless in symbolic mode.
1568 In symbolic mode, return the list (fn args)."
1569 (if calc-symbolic-mode
1570 (cons fn args)
1571 (apply fn args)))
1572
1573 (defun math-conditional-pow (a b)
1574 "Evaluate a^b unless in symbolic mode.
1575 In symbolic mode, return the list (^ a b)."
1576 (if calc-symbolic-mode
1577 (list '^ a b)
1578 (math-pow a b)))
1579
1580 (defun math-extract-logunits (expr)
1581 (if (memq (car-safe expr) '(* /))
1582 (cons (car expr)
1583 (mapcar 'math-extract-logunits (cdr expr)))
1584 (if (memq (car-safe expr) '(^))
1585 (list '^ (math-extract-logunits (nth 1 expr)) (nth 2 expr))
1586 (if (member expr math-logunits) expr 1))))
1587
1588 (defun math-logunits-add (a b neg power)
1589 (let ((aunit (math-simplify (math-extract-logunits a))))
1590 (if (not (eq (car-safe aunit) 'var))
1591 (calc-record-why "*Improper logarithmic unit" aunit)
1592 (let* ((units (math-extract-units a))
1593 (acoeff (math-simplify (math-remove-units a)))
1594 (bcoeff (math-simplify (math-to-standard-units
1595 (list '/ b units) nil))))
1596 (if (math-units-in-expr-p bcoeff nil)
1597 (calc-record-why "*Inconsistent units" nil)
1598 (if (and neg
1599 (or (math-lessp acoeff bcoeff)
1600 (math-equal acoeff bcoeff)))
1601 (calc-record-why "*Improper coefficients" nil)
1602 (math-mul
1603 (if (equal aunit '(var dB var-dB))
1604 (let ((coef (if power 10 20)))
1605 (math-mul coef
1606 (math-conditional-apply 'calcFunc-log10
1607 (if neg
1608 (math-sub
1609 (math-conditional-pow 10 (math-div acoeff coef))
1610 (math-conditional-pow 10 (math-div bcoeff coef)))
1611 (math-add
1612 (math-conditional-pow 10 (math-div acoeff coef))
1613 (math-conditional-pow 10 (math-div bcoeff coef)))))))
1614 (let ((coef (if power 2 1)))
1615 (math-div
1616 (math-conditional-apply 'calcFunc-ln
1617 (if neg
1618 (math-sub
1619 (math-conditional-apply 'calcFunc-exp (math-mul coef acoeff))
1620 (math-conditional-apply 'calcFunc-exp (math-mul coef bcoeff)))
1621 (math-add
1622 (math-conditional-apply 'calcFunc-exp (math-mul coef acoeff))
1623 (math-conditional-apply 'calcFunc-exp (math-mul coef bcoeff)))))
1624 coef)))
1625 units)))))))
1626
1627 (defun calcFunc-lufadd (a b)
1628 (math-logunits-add a b nil nil))
1629
1630 (defun calcFunc-lupadd (a b)
1631 (math-logunits-add a b nil t))
1632
1633 (defun calcFunc-lufsub (a b)
1634 (math-logunits-add a b t nil))
1635
1636 (defun calcFunc-lupsub (a b)
1637 (math-logunits-add a b t t))
1638
1639 (defun calc-lu-plus (arg)
1640 (interactive "P")
1641 (calc-slow-wrapper
1642 (if (calc-is-inverse)
1643 (if (calc-is-hyperbolic)
1644 (calc-binary-op "lu-" 'calcFunc-lufsub arg)
1645 (calc-binary-op "lu-" 'calcFunc-lupsub arg))
1646 (if (calc-is-hyperbolic)
1647 (calc-binary-op "lu+" 'calcFunc-lufadd arg)
1648 (calc-binary-op "lu+" 'calcFunc-lupadd arg)))))
1649
1650 (defun calc-lu-minus (arg)
1651 (interactive "P")
1652 (calc-slow-wrapper
1653 (if (calc-is-inverse)
1654 (if (calc-is-hyperbolic)
1655 (calc-binary-op "lu+" 'calcFunc-lufadd arg)
1656 (calc-binary-op "lu+" 'calcFunc-lupadd arg))
1657 (if (calc-is-hyperbolic)
1658 (calc-binary-op "lu-" 'calcFunc-lufsub arg)
1659 (calc-binary-op "lu-" 'calcFunc-lupsub arg)))))
1660
1661 (defun math-logunits-mul (a b power)
1662 (let (logunit coef units number)
1663 (cond
1664 ((and
1665 (setq logunit (math-simplify (math-extract-logunits a)))
1666 (eq (car-safe logunit) 'var)
1667 (eq (math-simplify (math-extract-units b)) 1))
1668 (setq coef (math-simplify (math-remove-units a))
1669 units (math-extract-units a)
1670 number b))
1671 ((and
1672 (setq logunit (math-simplify (math-extract-logunits b)))
1673 (eq (car-safe logunit) 'var)
1674 (eq (math-simplify (math-extract-units a)) 1))
1675 (setq coef (math-simplify (math-remove-units b))
1676 units (math-extract-units b)
1677 number a))
1678 (t (setq logunit nil)))
1679 (if logunit
1680 (cond
1681 ((equal logunit '(var dB var-dB))
1682 (math-simplify
1683 (math-mul
1684 (math-add
1685 coef
1686 (math-mul (if power 10 20)
1687 (math-conditional-apply 'calcFunc-log10 number)))
1688 units)))
1689 (t
1690 (math-simplify
1691 (math-mul
1692 (math-add
1693 coef
1694 (math-div (math-conditional-apply 'calcFunc-ln number) (if power 2 1)))
1695 units))))
1696 (calc-record-why "*Improper units" nil))))
1697
1698 (defun math-logunits-divide (a b power)
1699 (let ((logunit (math-simplify (math-extract-logunits a))))
1700 (if (not (eq (car-safe logunit) 'var))
1701 (calc-record-why "*Improper logarithmic unit" logunit)
1702 (if (math-units-in-expr-p b nil)
1703 (calc-record-why "*Improper units quantity" b)
1704 (let* ((units (math-extract-units a))
1705 (coef (math-simplify (math-remove-units a))))
1706 (cond
1707 ((equal logunit '(var dB var-dB))
1708 (math-simplify
1709 (math-mul
1710 (math-sub
1711 coef
1712 (math-mul (if power 10 20)
1713 (math-conditional-apply 'calcFunc-log10 b)))
1714 units)))
1715 (t
1716 (math-simplify
1717 (math-mul
1718 (math-sub
1719 coef
1720 (math-div (math-conditional-apply 'calcFunc-ln b) (if power 2 1)))
1721 units)))))))))
1722
1723 (defun calcFunc-lufmul (a b)
1724 (math-logunits-mul a b nil))
1725
1726 (defun calcFunc-lupmul (a b)
1727 (math-logunits-mul a b t))
1728
1729 (defun calc-lu-times (arg)
1730 (interactive "P")
1731 (calc-slow-wrapper
1732 (if (calc-is-inverse)
1733 (if (calc-is-hyperbolic)
1734 (calc-binary-op "lu/" 'calcFunc-lufdiv arg)
1735 (calc-binary-op "lu/" 'calcFunc-lupdiv arg))
1736 (if (calc-is-hyperbolic)
1737 (calc-binary-op "lu*" 'calcFunc-lufmul arg)
1738 (calc-binary-op "lu*" 'calcFunc-lupmul arg)))))
1739
1740 (defun calcFunc-lufdiv (a b)
1741 (math-logunits-divide a b nil))
1742
1743 (defun calcFunc-lupdiv (a b)
1744 (math-logunits-divide a b t))
1745
1746 (defun calc-lu-divide (arg)
1747 (interactive "P")
1748 (calc-slow-wrapper
1749 (if (calc-is-inverse)
1750 (if (calc-is-hyperbolic)
1751 (calc-binary-op "lu*" 'calcFunc-lufmul arg)
1752 (calc-binary-op "lu*" 'calcFunc-lupmul arg))
1753 (if (calc-is-hyperbolic)
1754 (calc-binary-op "lu/" 'calcFunc-lufdiv arg)
1755 (calc-binary-op "lu/" 'calcFunc-lupdiv arg)))))
1756
1757 (defun math-logunits-quant (val ref power)
1758 (let* ((units (math-simplify (math-extract-units val)))
1759 (lunit (math-simplify (math-extract-logunits units))))
1760 (if (not (eq (car-safe lunit) 'var))
1761 (calc-record-why "*Improper logarithmic unit" lunit)
1762 (let ((runits (math-simplify (math-div units lunit)))
1763 (coeff (math-simplify (math-div val units))))
1764 (math-mul
1765 (if (equal lunit '(var dB var-dB))
1766 (math-mul
1767 ref
1768 (math-conditional-pow
1769 10
1770 (math-div
1771 coeff
1772 (if power 10 20))))
1773 (math-mul
1774 ref
1775 (math-conditional-apply 'calcFunc-exp
1776 (if power
1777 (math-mul 2 coeff)
1778 coeff))))
1779 runits)))))
1780
1781 (defvar calc-lu-field-reference)
1782 (defvar calc-lu-power-reference)
1783
1784 (defun calcFunc-lufquant (val &optional ref)
1785 (unless ref
1786 (setq ref (math-read-expr calc-lu-field-reference)))
1787 (math-logunits-quant val ref nil))
1788
1789 (defun calcFunc-lupquant (val &optional ref)
1790 (unless ref
1791 (setq ref (math-read-expr calc-lu-power-reference)))
1792 (math-logunits-quant val ref t))
1793
1794 (defun calc-lu-quant (arg)
1795 (interactive "P")
1796 (calc-slow-wrapper
1797 (if (calc-is-hyperbolic)
1798 (if (calc-is-option)
1799 (calc-binary-op "lupq" 'calcFunc-lufquant arg)
1800 (calc-unary-op "lupq" 'calcFunc-lufquant arg))
1801 (if (calc-is-option)
1802 (calc-binary-op "lufq" 'calcFunc-lupquant arg)
1803 (calc-unary-op "lufq" 'calcFunc-lupquant arg)))))
1804
1805 (defun math-logunits-level (val ref db power)
1806 "Compute the value of VAL in decibels or nepers."
1807 (let* ((ratio (math-simplify-units (math-div val ref)))
1808 (ratiou (math-simplify-units (math-remove-units ratio)))
1809 (units (math-simplify (math-extract-units ratio))))
1810 (math-mul
1811 (if db
1812 (math-mul
1813 (math-mul (if power 10 20)
1814 (math-conditional-apply 'calcFunc-log10 ratiou))
1815 '(var dB var-dB))
1816 (math-mul
1817 (math-div (math-conditional-apply 'calcFunc-ln ratiou) (if power 2 1))
1818 '(var Np var-Np)))
1819 units)))
1820
1821 (defun calcFunc-dbfield (val &optional ref)
1822 (unless ref
1823 (setq ref (math-read-expr calc-lu-field-reference)))
1824 (math-logunits-level val ref t nil))
1825
1826 (defun calcFunc-dbpower (val &optional ref)
1827 (unless ref
1828 (setq ref (math-read-expr calc-lu-power-reference)))
1829 (math-logunits-level val ref t t))
1830
1831 (defun calcFunc-npfield (val &optional ref)
1832 (unless ref
1833 (setq ref (math-read-expr calc-lu-field-reference)))
1834 (math-logunits-level val ref nil nil))
1835
1836 (defun calcFunc-nppower (val &optional ref)
1837 (unless ref
1838 (setq ref (math-read-expr calc-lu-power-reference)))
1839 (math-logunits-level val ref nil t))
1840
1841 (defun calc-db (arg)
1842 (interactive "P")
1843 (calc-slow-wrapper
1844 (if (calc-is-hyperbolic)
1845 (if (calc-is-option)
1846 (calc-binary-op "ludb" 'calcFunc-dbfield arg)
1847 (calc-unary-op "ludb" 'calcFunc-dbfield arg))
1848 (if (calc-is-option)
1849 (calc-binary-op "ludb" 'calcFunc-dbpower arg)
1850 (calc-unary-op "ludb" 'calcFunc-dbpower arg)))))
1851
1852 (defun calc-np (arg)
1853 (interactive "P")
1854 (calc-slow-wrapper
1855 (if (calc-is-hyperbolic)
1856 (if (calc-is-option)
1857 (calc-binary-op "lunp" 'calcFunc-npfield arg)
1858 (calc-unary-op "lunp" 'calcFunc-npfield arg))
1859 (if (calc-is-option)
1860 (calc-binary-op "lunp" 'calcFunc-nppower arg)
1861 (calc-unary-op "lunp" 'calcFunc-nppower arg)))))
1862
1863 ;;; Musical notes
1864
1865
1866 (defvar calc-note-threshold)
1867
1868 (defun math-midi-round (num)
1869 "Round NUM to an integer N if NUM is within calc-note-threshold cents of N."
1870 (let* ((n (math-round num))
1871 (diff (math-abs
1872 (math-sub num n))))
1873 (if (< (math-compare diff
1874 (math-div (math-read-expr calc-note-threshold) 100)) 0)
1875 n
1876 num)))
1877
1878 (defconst math-notes
1879 '(((var C var-C) . 0)
1880 ((var Csharp var-Csharp) . 1)
1881 ; ((var C♯ var-C♯) . 1)
1882 ((var Dflat var-Dflat) . 1)
1883 ; ((var D♭ var-D♭) . 1)
1884 ((var D var-D) . 2)
1885 ((var Dsharp var-Dsharp) . 3)
1886 ; ((var D♯ var-D♯) . 3)
1887 ((var E var-E) . 4)
1888 ((var F var-F) . 5)
1889 ((var Fsharp var-Fsharp) . 6)
1890 ; ((var F♯ var-F♯) . 6)
1891 ((var Gflat var-Gflat) . 6)
1892 ; ((var G♭ var-G♭) . 6)
1893 ((var G var-G) . 7)
1894 ((var Gsharp var-Gsharp) . 8)
1895 ; ((var G♯ var-G♯) . 8)
1896 ((var A var-A) . 9)
1897 ((var Asharp var-Asharp) . 10)
1898 ; ((var A♯ var-A♯) . 10)
1899 ((var Bflat var-Bflat) . 10)
1900 ; ((var B♭ var-B♭) . 10)
1901 ((var B var-B) . 11))
1902 "An alist of notes with their number of semitones above C.")
1903
1904 (defun math-freqp (freq)
1905 "Non-nil if FREQ is a positive number times the unit Hz.
1906 If non-nil, return the coefficient of Hz."
1907 (let ((freqcoef (math-simplify-units
1908 (math-div freq '(var Hz var-Hz)))))
1909 (if (Math-posp freqcoef) freqcoef)))
1910
1911 (defun math-midip (num)
1912 "Non-nil if NUM is a possible MIDI note number.
1913 If non-nil, return NUM."
1914 (if (Math-numberp num) num))
1915
1916 (defun math-spnp (spn)
1917 "Non-nil if NUM is a scientific pitch note (note + cents).
1918 If non-nil, return a list consisting of the note and the cents coefficient."
1919 (let (note cents rnote rcents)
1920 (if (eq (car-safe spn) '+)
1921 (setq note (nth 1 spn)
1922 cents (nth 2 spn))
1923 (setq note spn
1924 cents nil))
1925 (cond
1926 ((and ;; NOTE is a note, CENTS is nil or cents.
1927 (eq (car-safe note) 'calcFunc-subscr)
1928 (assoc (nth 1 note) math-notes)
1929 (integerp (nth 2 note))
1930 (setq rnote note)
1931 (or
1932 (not cents)
1933 (Math-numberp (setq rcents
1934 (math-simplify
1935 (math-div cents '(var cents var-cents)))))))
1936 (list rnote rcents))
1937 ((and ;; CENTS is a note, NOTE is cents.
1938 (eq (car-safe cents) 'calcFunc-subscr)
1939 (assoc (nth 1 cents) math-notes)
1940 (integerp (nth 2 cents))
1941 (setq rnote cents)
1942 (or
1943 (not note)
1944 (Math-numberp (setq rcents
1945 (math-simplify
1946 (math-div note '(var cents var-cents)))))))
1947 (list rnote rcents)))))
1948
1949 (defun math-freq-to-midi (freq)
1950 "Return the midi note number corresponding to FREQ Hz."
1951 (let ((midi (math-add
1952 69
1953 (math-mul
1954 12
1955 (calcFunc-log
1956 (math-div freq 440)
1957 2)))))
1958 (math-midi-round midi)))
1959
1960 (defun math-spn-to-midi (spn)
1961 "Return the MIDI number corresponding to SPN."
1962 (let* ((note (cdr (assoc (nth 1 (car spn)) math-notes)))
1963 (octave (math-add (nth 2 (car spn)) 1))
1964 (cents (nth 1 spn))
1965 (midi (math-add
1966 (math-mul 12 octave)
1967 note)))
1968 (if cents
1969 (math-add midi (math-div cents 100))
1970 midi)))
1971
1972 (defun math-midi-to-spn (midi)
1973 "Return the scientific pitch notation corresponding to midi number MIDI."
1974 (let (midin cents)
1975 (if (math-integerp midi)
1976 (setq midin midi
1977 cents nil)
1978 (setq midin (math-floor midi)
1979 cents (math-mul 100 (math-sub midi midin))))
1980 (let* ((nr ;; This should be (math-idivmod midin 12), but with
1981 ;; better behavior for negative midin.
1982 (if (Math-negp midin)
1983 (let ((dm (math-idivmod (math-neg midin) 12)))
1984 (if (= (cdr dm) 0)
1985 (cons (math-neg (car dm)) 0)
1986 (cons
1987 (math-sub (math-neg (car dm)) 1)
1988 (math-sub 12 (cdr dm)))))
1989 (math-idivmod midin 12)))
1990 (n (math-sub (car nr) 1))
1991 (note (car (rassoc (cdr nr) math-notes))))
1992 (if cents
1993 (list '+ (list 'calcFunc-subscr note n)
1994 (list '* cents '(var cents var-cents)))
1995 (list 'calcFunc-subscr note n)))))
1996
1997 (defun math-freq-to-spn (freq)
1998 "Return the scientific pitch notation corresponding to FREQ Hz."
1999 (math-with-extra-prec 3
2000 (math-midi-to-spn (math-freq-to-midi freq))))
2001
2002 (defun math-midi-to-freq (midi)
2003 "Return the frequency of the note with midi number MIDI."
2004 (list '*
2005 (math-mul
2006 440
2007 (math-pow
2008 2
2009 (math-div
2010 (math-sub
2011 midi
2012 69)
2013 12)))
2014 '(var Hz var-Hz)))
2015
2016 (defun math-spn-to-freq (spn)
2017 "Return the frequency of the note with scientific pitch notation SPN."
2018 (math-midi-to-freq (math-spn-to-midi spn)))
2019
2020 (defun calcFunc-spn (expr)
2021 "Return EXPR written as scientific pitch notation + cents."
2022 ;; Get the coefficient of Hz
2023 (let (note)
2024 (cond
2025 ((setq note (math-freqp expr))
2026 (math-freq-to-spn note))
2027 ((setq note (math-midip expr))
2028 (math-midi-to-spn note))
2029 ((math-spnp expr)
2030 expr)
2031 (t
2032 (math-reject-arg expr "*Improper expression")))))
2033
2034 (defun calcFunc-midi (expr)
2035 "Return EXPR written as a MIDI number."
2036 (let (note)
2037 (cond
2038 ((setq note (math-freqp expr))
2039 (math-freq-to-midi note))
2040 ((setq note (math-spnp expr))
2041 (math-spn-to-midi note))
2042 ((math-midip expr)
2043 expr)
2044 (t
2045 (math-reject-arg expr "*Improper expression")))))
2046
2047 (defun calcFunc-freq (expr)
2048 "Return the frequency corresponding to EXPR."
2049 (let (note)
2050 (cond
2051 ((setq note (math-midip expr))
2052 (math-midi-to-freq note))
2053 ((setq note (math-spnp expr))
2054 (math-spn-to-freq note))
2055 ((math-freqp expr)
2056 expr)
2057 (t
2058 (math-reject-arg expr "*Improper expression")))))
2059
2060 (defun calc-freq (arg)
2061 "Return the frequency corresponding to the expression on the stack."
2062 (interactive "P")
2063 (calc-slow-wrapper
2064 (calc-unary-op "freq" 'calcFunc-freq arg)))
2065
2066 (defun calc-midi (arg)
2067 "Return the MIDI number corresponding to the expression on the stack."
2068 (interactive "P")
2069 (calc-slow-wrapper
2070 (calc-unary-op "midi" 'calcFunc-midi arg)))
2071
2072 (defun calc-spn (arg)
2073 "Return the scientific pitch notation corresponding to the expression on the stack."
2074 (interactive "P")
2075 (calc-slow-wrapper
2076 (calc-unary-op "spn" 'calcFunc-spn arg)))
2077
2078
2079 (provide 'calc-units)
2080
2081 ;; Local variables:
2082 ;; coding: utf-8
2083 ;; End:
2084
2085 ;;; calc-units.el ends here