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