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