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