UNPKG

21.6 kBMarkdownView Raw
1# Units
2
3Math.js supports units. Units can be used to do calculations and to perform
4conversions.
5
6## Usage
7
8Units can be created using the function `math.unit`. This function accepts
9either a single string argument containing a value and unit, or two arguments,
10the first being a numeric value and the second a string containing a unit.
11Most units support prefixes like `k` or `kilo`, and many units have both a
12full name and an abbreviation. The returned object is a `Unit`.
13
14Syntax:
15
16```js
17math.unit(value: number, name: string) : Unit
18math.unit(unit: string) : Unit
19math.unit(unit: Unit) : Unit
20```
21
22Example usage:
23
24```js
25const a = math.unit(45, 'cm') // Unit 450 mm
26const b = math.unit('0.1 kilogram') // Unit 100 gram
27const c = math.unit('2 inch') // Unit 2 inch
28const d = math.unit('90 km/h') // Unit 90 km/h
29const e = math.unit('101325 kg/(m s^2)') // Unit 101325 kg / (m s^2)
30
31const d = c.to('cm') // Unit 5.08 cm
32b.toNumber('gram') // Number 100
33math.number(b, 'gram') // Number 100
34
35c.equals(a) // false
36c.equals(d) // true
37c.equalBase(a) // true
38c.equalBase(b) // false
39
40d.toString() // String "5.08 cm"
41```
42
43Use care when creating a unit with multiple terms in the denominator. Implicit multiplication has the same operator precedence as explicit multiplication and division, which means these three expressions are identical:
44
45```js
46// These three are identical
47const correct1 = math.unit('8.314 m^3 Pa / mol / K') // Unit 8.314 (m^3 Pa) / (mol K)
48const correct2 = math.unit('8.314 (m^3 Pa) / (mol K)') // Unit 8.314 (m^3 Pa) / (mol K)
49const correct3 = math.unit('8.314 (m^3 * Pa) / (mol * K)') // Unit 8.314 (m^3 Pa) / (mol K)
50```
51But this expression, which omits the second `/` between `mol` and `K`, results in the wrong value:
52
53```js
54// Missing the second '/' between 'mol' and 'K'
55const incorrect = math.unit('8.314 m^3 Pa / mol K') // Unit 8.314 (m^3 Pa K) / mol
56```
57
58## Calculations
59
60The operations that support units are `add`, `subtract`, `multiply`, `divide`, `pow`, `abs`, `sqrt`, `square`, `cube`, and `sign`.
61Trigonometric functions like `cos` are also supported when the argument is an angle.
62
63```js
64const a = math.unit(45, 'cm') // Unit 450 mm
65const b = math.unit('0.1m') // Unit 100 mm
66math.add(a, b) // Unit 0.65 m
67math.multiply(b, 2) // Unit 200 mm
68
69const c = math.unit(45, 'deg') // Unit 45 deg
70math.cos(c) // Number 0.7071067811865476
71
72// Kinetic energy of average sedan on highway
73const d = math.unit('80 mi/h') // Unit 80 mi/h
74const e = math.unit('2 tonne') // Unit 2 tonne
75const f = math.multiply(0.5, math.multipy(math.pow(d, 2), e))
76 // 1.2790064742399996 MJ
77```
78
79Operations with arrays are supported too:
80
81```js
82// Force on a charged particle moving through a magnetic field
83const B = math.evaluate('[1, 0, 0] T') // [1 T, 0 T, 0 T]
84const v = math.evaluate('[0, 1, 0] m/s') // [0 m / s, 1 m / s, 0 m / s]
85const q = math.evaluate('1 C') // 1 C
86
87const F = math.multiply(q, math.cross(v, B)) // [0 N, 0 N, -1 N]
88```
89
90All arithmetic operators act on the value of the unit as it is represented in SI units.
91This may lead to surprising behavior when working with temperature scales like `celsius` (or `degC`) and `fahrenheit` (or `degF`).
92In general you should avoid calculations using `celsius` and `fahrenheit`. Rather, use `kelvin` (or `K`) and `rankine` (or `R`) instead.
93This example highlights some problems when using `celsius` and `fahrenheit` in calculations:
94
95```js
96const T_14F = math.unit('14 degF') // Unit 14 degF (263.15 K)
97const T_28F = math.multiply(T1, 2) // Unit 487.67 degF (526.3 K), not 28 degF
98
99const Tnegative = math.unit(-13, 'degF') // Unit -13 degF (248.15 K)
100const Tpositive = math.abs(T1) // Unit -13 degF (248.15 K), not 13 degF
101
102const Trate1 = math.evaluate('5 (degC/hour)') // Unit 5 degC/hour
103const Trate2 = math.evaluate('(5 degC)/hour') // Unit 278.15 degC/hour
104```
105
106The expression parser supports units too. This is described in the section about
107units on the page [Syntax](../expressions/syntax.md#units).
108
109## User-Defined Units
110
111You can add your own units to Math.js using the `math.createUnit` function. The following example defines a new unit `furlong`, then uses the user-defined unit in a calculation:
112
113```js
114math.createUnit('furlong', '220 yards')
115math.evaluate('1 mile to furlong') // 8 furlong
116```
117
118If you cannot express the new unit in terms of any existing unit, then the second argument can be omitted. In this case, a new *base unit* is created:
119
120```js
121// A 'foo' cannot be expressed in terms of any other unit.
122math.createUnit('foo')
123math.evaluate('8 foo * 4 feet') // 32 foo feet
124```
125
126The second argument to `createUnit` can also be a configuration object consisting of the following properties:
127
128* **definition** A `string` or `Unit` which defines the user-defined unit in terms of existing built-in or user-defined units. If omitted, a new base unit is created.
129* **prefixes** A `string` indicating which prefixes math.js should use with the new unit. Possible values are `'none'`, `'short'`, `'long'`, `'binary_short'`, or `'binary_long'`. Default is `'none'`.
130* **offset** A value applied when converting to the unit. This is very helpful for temperature scales that do not share a zero with the absolute temperature scale. For example, if we were defining fahrenheit for the first time, we would use: `math.createUnit('fahrenheit', {definition: '0.555556 kelvin', offset: 459.67})`
131* **aliases** An array of strings to alias the new unit. Example: `math.createUnit('knot', {definition: '0.514444 m/s', aliases: ['knots', 'kt', 'kts']})`
132* **baseName** A `string` that specifies the name of the new dimension in case one needs to be created. Every unit in math.js has a dimension: length, time, velocity, etc. If the unit's `definition` doesn't match any existing dimension, or it is a new base unit, then `createUnit` will create a new dimension with the name `baseName` and assign it to the new unit. The default is to append `'_STUFF'` to the unit's name. If the unit already matches an existing dimension, this option has no effect.
133
134An optional `options` object can also be supplied as the last argument to `createUnits`. Currently only the `override` option is supported:
135
136```js
137// Redefine the mile (would not be the first time in history)
138math.createUnit('mile', '1609.347218694', {override: true}})
139```
140Base units created without specifying a definition cannot be overridden.
141
142### Create several units at once
143Multiple units can defined using a single call to `createUnit` by passing an object map as the first argument, where each key in the object is the name of a new unit and the value is either a string defining the unit, or an object with the configuration properties listed above. If the value is an empty string or an object lacking a definition property, a new base unit is created.
144
145For example:
146
147```js
148math.createUnit( {
149 foo: {
150 prefixes: 'long',
151 baseName: 'essence-of-foo'
152 },
153 bar: '40 foo',
154 baz: {
155 definition: '1 bar/hour',
156 prefixes: 'long'
157 }
158},
159{
160 override: true
161})
162math.evaluate('50000 kilofoo/s') // 4.5 gigabaz
163```
164
165### Return Value
166`createUnit` returns the created unit, or, when multiple units are created, the last unit created. Since `createUnit` is also compatible with the expression parser, this allows you to do things like this:
167
168```js
169math.evaluate('45 mile/hour to createUnit("knot", "0.514444m/s")')
170// 39.103964668651976 knot
171```
172
173### Support of custom characters in unit names
174Per default, the name of a new unit:
175- should start by a latin (A-Z or a-z) character
176- should contain only numeric (0-9) or latin characters
177
178It is possible to allow the usage of special characters (such as Greek alphabet, cyrillic alphabet, any Unicode symbols, etc.) by overriding the `Unit.isValidAlpha` static method. For example:
179```js
180const isAlphaOriginal = math.Unit.isValidAlpha
181const isGreekLowercaseChar = function (c) {
182 const charCode = c.charCodeAt(0)
183 return charCode > 944 && charCode < 970
184}
185math.Unit.isValidAlpha = function (c) {
186 return isAlphaOriginal(c) || isGreekLowercaseChar(c)
187}
188
189math.createUnit('θ', '1 rad')
190math.evaluate('1θ + 3 deg').toNumber('deg') // 60.29577951308232
191```
192
193## API
194A `Unit` object contains the following functions:
195
196### unit.clone()
197Clone the unit, returns a new unit with the same parameters.
198
199### unit.equalBase(unit)
200Test whether a unit has the same base as an other unit:
201length, mass, etc.
202
203### unit.equals(unit)
204Test whether a unit equals an other unit. Units are equal
205when they have the same base and same value when normalized to SI units.
206
207### unit.format([options])
208Get a string representation of the unit. The function
209will determine the best fitting prefix for the unit. See the [Format](../reference/functions/format.md)
210page for available options.
211
212### unit.fromJSON(json)
213Revive a unit from a JSON object. Accepts
214An object `{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`,
215where the property `mathjs` and `fixPrefix` are optional.
216Used when deserializing a unit, see [Serialization](../core/serialization.md).
217
218### unit.splitUnit(parts)
219Split a unit into the specified parts. For example:
220
221```js
222const u = math.unit(1, 'm')
223u.splitUnit(['ft', 'in']) // 3 feet,3.3700787401574765 inch
224```
225
226### unit.to(unitName)
227Convert the unit to a specific unit name. Returns a clone of
228the unit with a fixed prefix and unit.
229
230### unit.toJSON()
231Returns a JSON representation of the unit, with signature
232`{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`.
233Used when serializing a unit, see [Serialization](../core/serialization.md).
234
235### unit.toNumber(unitName)
236Get the value of a unit when converted to the
237specified unit (a unit with optional prefix but without value).
238The type of the returned value is always `number`.
239
240### unit.toNumeric(unitName)
241Get the value of a unit when converted to the
242specified unit (a unit with optional prefix but without value).
243The type of the returned value depends on how the unit was created and
244can be `number`, `Fraction`, or `BigNumber`.
245
246### unit.toSI()
247Returns a clone of a unit represented in SI units. Works with units with or without a value.
248
249### unit.toString()
250Get a string representation of the unit. The function will
251determine the best fitting prefix for the unit.
252
253## Unit reference
254
255This section lists all available units, prefixes, and physical constants. These can be used via the Unit object, or via `math.evaluate()`.
256
257## Reference
258
259Math.js comes with the following built-in units.
260
261Base | Unit
262------------------- | ---
263Length | meter (m), inch (in), foot (ft), yard (yd), mile (mi), link (li), rod (rd), chain (ch), angstrom, mil
264Surface area | m2, sqin, sqft, sqyd, sqmi, sqrd, sqch, sqmil, acre, hectare
265Volume | m3, litre (l, L, lt, liter), cc, cuin, cuft, cuyd, teaspoon, tablespoon
266Liquid volume | minim (min), fluiddram (fldr), fluidounce (floz), gill (gi), cup (cp), pint (pt), quart (qt), gallon (gal), beerbarrel (bbl), oilbarrel (obl), hogshead, drop (gtt)
267Angles | rad (radian), deg (degree), grad (gradian), cycle, arcsec (arcsecond), arcmin (arcminute)
268Time | second (s, secs, seconds), minute (mins, minutes), hour (h, hr, hrs, hours), day (days), week (weeks), month (months), year (years), decade (decades), century (centuries), millennium (millennia)
269Frequency | hertz (Hz)
270Mass | gram(g), tonne, ton, grain (gr), dram (dr), ounce (oz), poundmass (lbm, lb, lbs), hundredweight (cwt), stick, stone
271Electric current | ampere (A)
272Temperature | kelvin (K), celsius (degC), fahrenheit (degF), rankine (degR)
273Amount of substance | mole (mol)
274Luminous intensity | candela (cd)
275Force | newton (N), dyne (dyn), poundforce (lbf), kip
276Energy | joule (J), erg, Wh, BTU, electronvolt (eV)
277Power | watt (W), hp
278Pressure | Pa, psi, atm, torr, bar, mmHg, mmH2O, cmH2O
279Electricity and magnetism | ampere (A), coulomb (C), watt (W), volt (V), ohm, farad (F), weber (Wb), tesla (T), henry (H), siemens (S), electronvolt (eV)
280Binary | bits (b), bytes (B)
281
282Note: all time units are based on the Julian year, with one month being 1/12th of a Julian year, a year being one Julian year, a decade being 10 Julian years, a century being 100, and a millennium being 1000.
283
284Note that all relevant units can also be written in plural form, for example `5 meters` instead of `5 meter` or `10 seconds` instead of `10 second`.
285
286Surface and volume units can alternatively be expressed in terms of length units raised to a power, for example `100 in^2` instead of `100 sqin`.
287
288### Prefixes
289
290The following decimal prefixes are available.
291
292Name | Abbreviation | Value
293------- | ------------- | -----
294deca | da | 1e1
295hecto | h | 1e2
296kilo | k | 1e3
297mega | M | 1e6
298giga | G | 1e9
299tera | T | 1e12
300peta | P | 1e15
301exa | E | 1e18
302zetta | Z | 1e21
303yotta | Y | 1e24
304
305Name | Abbreviation | Value
306------ | ------------- | -----
307deci | d | 1e-1
308centi | c | 1e-2
309milli | m | 1e-3
310micro | u | 1e-6
311nano | n | 1e-9
312pico | p | 1e-12
313femto | f | 1e-15
314atto | a | 1e-18
315zepto | z | 1e-21
316yocto | y | 1e-24
317
318The following binary prefixes are available.
319They can be used with units `bits` (`b`) and `bytes` (`B`).
320
321Name | Abbreviation | Value
322---- | ------------ | -----
323kibi | Ki | 1024
324mebi | Mi | 1024^2
325gibi | Gi | 1024^3
326tebi | Ti | 1024^4
327pebi | Pi | 1024^5
328exi | Ei | 1024^6
329zebi | Zi | 1024^7
330yobi | Yi | 1024^8
331
332Name | Abbreviation | Value
333----- | ------------ | -----
334kilo | k | 1e3
335mega | M | 1e6
336giga | G | 1e9
337tera | T | 1e12
338peta | P | 1e15
339exa | E | 1e18
340zetta | Z | 1e21
341yotta | Y | 1e24
342
343
344### Physical Constants
345
346Math.js includes the following physical constants. See [Wikipedia](https://en.wikipedia.org/wiki/Physical_constants) for more information.
347
348
349#### Universal constants
350
351Name | Symbol | Value | Unit
352----------------------|--------------------------------------------------------|-------------------|-------------------------------------------------------
353speedOfLight | <i>c</i> | 299792458 | m &#183; s<sup>-1</sup>
354gravitationConstant | <i>G</i> | 6.6738480e-11 | m<sup>3</sup> &#183; kg<sup>-1</sup> &#183; s<sup>-2</sup>
355planckConstant | <i>h</i> | 6.626069311e-34 | J &#183; s
356reducedPlanckConstant | <i><span style="text-decoration:overline">h</span></i> | 1.05457172647e-34 | J &#183; s
357
358
359#### Electromagnetic constants
360
361Name | Symbol | Value | Unit
362--------------------------|--------------------------------------------------|-----------------------|----------------------------------------
363magneticConstant | <i>&mu;<sub>0</sub></i> | 1.2566370614e-6 | N &#183; A<sup>-2</sup>
364electricConstant | <i>&epsilon;<sub>0</sub></i> | 8.854187817e-12 | F &#183; m<sup>-1</sup>
365vacuumImpedance | <i>Z<sub>0</sub></i> | 376.730313461 | &ohm;
366coulomb | <i>&kappa;</i> | 8.9875517873681764e9 | N &#183; m<sup>2</sup> &#183; C<sup>-2</sup>
367elementaryCharge | <i>e</i> | 1.60217656535e-19 | C
368bohrMagneton | <i>&mu;<sub>B</sub></i> | 9.2740096820e-24 | J &#183; T<sup>-1</sup>
369conductanceQuantum | <i>G<sub>0</sub></i> | 7.748091734625e-5 | S
370inverseConductanceQuantum | <i>G<sub>0</sub><sup>-1</sup></i> | 12906.403721742 | &ohm;
371magneticFluxQuantum | <i><font face="Symbol">f</font><sub>0</sub></i> | 2.06783375846e-15 | Wb
372nuclearMagneton | <i>&mu;<sub>N</sub></i> | 5.0507835311e-27 | J &#183; T<sup>-1</sup>
373klitzing | <i>R<sub>K</sub></i> | 25812.807443484 | &ohm;
374
375<!-- TODO: implement josephson
376josephson | <i>K<sub>J</sub></i> | 4.8359787011e-14 | Hz &#183; V<sup>-1</sup>
377-->
378
379
380#### Atomic and nuclear constants
381
382Name | Symbol | Value | Unit
383------------------------|------------------------------|-----------------------|----------------------------------
384bohrRadius | <i>a<sub>0</sub></i> | 5.291772109217e-11 | m
385classicalElectronRadius | <i>r<sub>e</sub></i> | 2.817940326727e-15 | m
386electronMass | <i>m<sub>e</sub></i> | 9.1093829140e-31 | kg
387fermiCoupling | <i>G<sub>F</sub></i> | 1.1663645e-5 | GeV<sup>-2</sup>
388fineStructure | <i>&alpha;</i> | 7.297352569824e-3 | -
389hartreeEnergy | <i>E<abbr>h</abbr> </i> | 4.3597443419e-18 | J
390protonMass | <i>m<sub>p</sub></i> | 1.67262177774e-27 | kg
391deuteronMass | <i>m<sub>d</sub></i> | 3.3435830926e-27 | kg
392neutronMass | <i>m<sub>n</sub></i> | 1.6749271613e-27 | kg
393quantumOfCirculation | <i>h / (2m<sub>e</sub>)</i> | 3.636947552024e-4 | m<sup>2</sup> &#183; s<sup>-1</sup>
394rydberg | <i>R<sub>&infin;</sub></i> | 10973731.56853955 | m<sup>-1</sup>
395thomsonCrossSection | | 6.65245873413e-29 | m<sup>2</sup>
396weakMixingAngle | | 0.222321 | -
397efimovFactor | | 22.7 | -
398
399
400#### Physico-chemical constants
401
402Name | Symbol | Value | Unit
403--------------------|------------------------------|---------------------|--------------------------------------------
404atomicMass | <i>m<sub>u</sub></i> | 1.66053892173e-27 | kg
405avogadro | <i>N<sub>A</sub></i> | 6.0221412927e23 | mol<sup>-1</sup>
406boltzmann | <i>k</i> | 1.380648813e-23 | J &#183; K<sup>-1</sup>
407faraday | <i>F</i> | 96485.336521 | C &#183; mol<sup>-1</sup>
408firstRadiation | <i>c<sub>1</sub></i> | 3.7417715317e-16 | W &#183; m<sup>2</sup>
409loschmidt | <i>n<sub>0</sub></i> | 2.686780524e25 | m<sup>-3</sup>
410gasConstant | <i>R</i> | 8.314462175 | J &#183; K<sup>-1</sup> &#183; mol<sup>-1</sup>
411molarPlanckConstant | <i>N<sub>A</sub> &#183; h</i>| 3.990312717628e-10| J &#183; s &#183; mol<sup>-1</sup>
412molarVolume | <i>V<sub>m</sub></i> | 2.241396820e-10 | m<sup>3</sup> &#183; mol<sup>-1</sup>
413sackurTetrode | | -1.164870823 | -
414secondRadiation | <i>c<sub>2</sub></i> | 1.438777013e-2 | m &#183; K
415stefanBoltzmann | <i>&sigma;</i> | 5.67037321e-8 | W &#183; m<sup>-2</sup> &#183; K<sup>-4</sup>
416wienDisplacement | <i>b</i> | 2.897772126e-3 | m &#183; K
417
418<!-- TODO: implement spectralRadiance
419spectralRadiance | <i>c<sub>1L</sub></i> | 1.19104286953e-16 | W &#183; m<sup>2</sup> &#183; sr<sup>-1</sup>
420-->
421
422Note that the values of `loschmidt` and `molarVolume` are at `T = 273.15 K` and `p = 101.325 kPa`.
423The value of `sackurTetrode` is at `T = 1 K` and `p = 101.325 kPa`.
424
425
426#### Adopted values
427
428Name | Symbol | Value | Unit
429--------------|------------------------------|---------|-------------------------
430molarMass | <i>M<sub>u</sub></i> | 1e-3 | kg &#183; mol<sup>-1</sup>
431molarMassC12 | <i>M(<sub>12</sub>C)</i> | 1.2e-2 | kg &#183; mol<sup>-1</sup>
432gravity | <i>g<sub>n</sub></i> | 9.80665 | m &#183; s<sup>-2</sup>
433atm | <i>atm</i> | 101325 | Pa
434
435
436#### Natural units
437
438Name | Symbol | Value | Unit
439------------------|-----------------------|--------------------|-----
440planckLength | <i>l<sub>P</sub></i> | 1.61619997e-35 | m
441planckMass | <i>m<sub>P</sub></i> | 2.1765113e-8 | kg
442planckTime | <i>t<sub>P</sub></i> | 5.3910632e-44 | s
443planckCharge | <i>q<sub>P</sub></i> | 1.87554595641e-18 | C
444planckTemperature | <i>T<sub>P</sub></i> | 1.41683385e+32 | K