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