UNPKG

20.8 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
142Multiple 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.
143
144For example:
145
146```js
147math.createUnit( {
148 foo: {
149 prefixes: 'long',
150 baseName: 'essence-of-foo'
151 },
152 bar: '40 foo',
153 baz: {
154 definition: '1 bar/hour',
155 prefixes: 'long'
156 }
157},
158{
159 override: true
160})
161math.evaluate('50000 kilofoo/s') // 4.5 gigabaz
162```
163
164### Return Value
165`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:
166
167```js
168math.evaluate('45 mile/hour to createUnit("knot", "0.514444m/s")')
169// 39.103964668651976 knot
170```
171
172## API
173A `Unit` object contains the following functions:
174
175### unit.clone()
176Clone the unit, returns a new unit with the same parameters.
177
178### unit.equalBase(unit)
179Test whether a unit has the same base as an other unit:
180length, mass, etc.
181
182### unit.equals(unit)
183Test whether a unit equals an other unit. Units are equal
184when they have the same base and same value when normalized to SI units.
185
186### unit.format([options])
187Get a string representation of the unit. The function
188will determine the best fitting prefix for the unit. See the [Format](../reference/functions/format.md)
189page for available options.
190
191### unit.fromJSON(json)
192Revive a unit from a JSON object. Accepts
193An object `{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`,
194where the property `mathjs` and `fixPrefix` are optional.
195Used when deserializing a unit, see [Serialization](../core/serialization.md).
196
197### unit.splitUnit(parts)
198Split a unit into the specified parts. For example:
199
200```js
201const u = math.unit(1, 'm')
202u.splitUnit(['ft', 'in']) // 3 feet,3.3700787401574765 inch
203```
204
205### unit.to(unitName)
206Convert the unit to a specific unit name. Returns a clone of
207the unit with a fixed prefix and unit.
208
209### unit.toJSON()
210Returns a JSON representation of the unit, with signature
211`{mathjs: 'Unit', value: number, unit: string, fixPrefix: boolean}`.
212Used when serializing a unit, see [Serialization](../core/serialization.md).
213
214### unit.toNumber(unitName)
215Get the value of a unit when converted to the
216specified unit (a unit with optional prefix but without value).
217The type of the returned value is always `number`.
218
219### unit.toNumeric(unitName)
220Get the value of a unit when converted to the
221specified unit (a unit with optional prefix but without value).
222The type of the returned value depends on how the unit was created and
223can be `number`, `Fraction`, or `BigNumber`.
224
225### unit.toSI()
226Returns a clone of a unit represented in SI units. Works with units with or without a value.
227
228### unit.toString()
229Get a string representation of the unit. The function will
230determine the best fitting prefix for the unit.
231
232## Unit reference
233
234This section lists all available units, prefixes, and physical constants. These can be used via the Unit object, or via `math.evaluate()`.
235
236## Reference
237
238Math.js comes with the following built-in units.
239
240Base | Unit
241------------------- | ---
242Length | meter (m), inch (in), foot (ft), yard (yd), mile (mi), link (li), rod (rd), chain (ch), angstrom, mil
243Surface area | m2, sqin, sqft, sqyd, sqmi, sqrd, sqch, sqmil, acre, hectare
244Volume | m3, litre (l, L, lt, liter), cc, cuin, cuft, cuyd, teaspoon, tablespoon
245Liquid volume | minim (min), fluiddram (fldr), fluidounce (floz), gill (gi), cup (cp), pint (pt), quart (qt), gallon (gal), beerbarrel (bbl), oilbarrel (obl), hogshead, drop (gtt)
246Angles | rad (radian), deg (degree), grad (gradian), cycle, arcsec (arcsecond), arcmin (arcminute)
247Time | 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)
248Frequency | hertz (Hz)
249Mass | gram(g), tonne, ton, grain (gr), dram (dr), ounce (oz), poundmass (lbm, lb, lbs), hundredweight (cwt), stick, stone
250Electric current | ampere (A)
251Temperature | kelvin (K), celsius (degC), fahrenheit (degF), rankine (degR)
252Amount of substance | mole (mol)
253Luminous intensity | candela (cd)
254Force | newton (N), dyne (dyn), poundforce (lbf), kip
255Energy | joule (J), erg, Wh, BTU, electronvolt (eV)
256Power | watt (W), hp
257Pressure | Pa, psi, atm, torr, bar, mmHg, mmH2O, cmH2O
258Electricity and magnetism | ampere (A), coulomb (C), watt (W), volt (V), ohm, farad (F), weber (Wb), tesla (T), henry (H), siemens (S), electronvolt (eV)
259Binary | bits (b), bytes (B)
260
261Note: 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.
262
263Note 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`.
264
265Surface 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`.
266
267### Prefixes
268
269The following decimal prefixes are available.
270
271Name | Abbreviation | Value
272------- | ------------- | -----
273deca | da | 1e1
274hecto | h | 1e2
275kilo | k | 1e3
276mega | M | 1e6
277giga | G | 1e9
278tera | T | 1e12
279peta | P | 1e15
280exa | E | 1e18
281zetta | Z | 1e21
282yotta | Y | 1e24
283
284Name | Abbreviation | Value
285------ | ------------- | -----
286deci | d | 1e-1
287centi | c | 1e-2
288milli | m | 1e-3
289micro | u | 1e-6
290nano | n | 1e-9
291pico | p | 1e-12
292femto | f | 1e-15
293atto | a | 1e-18
294zepto | z | 1e-21
295yocto | y | 1e-24
296
297The following binary prefixes are available.
298They can be used with units `bits` (`b`) and `bytes` (`B`).
299
300Name | Abbreviation | Value
301---- | ------------ | -----
302kibi | Ki | 1024
303mebi | Mi | 1024^2
304gibi | Gi | 1024^3
305tebi | Ti | 1024^4
306pebi | Pi | 1024^5
307exi | Ei | 1024^6
308zebi | Zi | 1024^7
309yobi | Yi | 1024^8
310
311Name | Abbreviation | Value
312----- | ------------ | -----
313kilo | k | 1e3
314mega | M | 1e6
315giga | G | 1e9
316tera | T | 1e12
317peta | P | 1e15
318exa | E | 1e18
319zetta | Z | 1e21
320yotta | Y | 1e24
321
322
323### Physical Constants
324
325Math.js includes the following physical constants. See [Wikipedia](https://en.wikipedia.org/wiki/Physical_constants) for more information.
326
327
328#### Universal constants
329
330Name | Symbol | Value | Unit
331----------------------|--------------------------------------------------------|-------------------|-------------------------------------------------------
332speedOfLight | <i>c</i> | 299792458 | m &#183; s<sup>-1</sup>
333gravitationConstant | <i>G</i> | 6.6738480e-11 | m<sup>3</sup> &#183; kg<sup>-1</sup> &#183; s<sup>-2</sup>
334planckConstant | <i>h</i> | 6.626069311e-34 | J &#183; s
335reducedPlanckConstant | <i><span style="text-decoration:overline">h</span></i> | 1.05457172647e-34 | J &#183; s
336
337
338#### Electromagnetic constants
339
340Name | Symbol | Value | Unit
341--------------------------|--------------------------------------------------|-----------------------|----------------------------------------
342magneticConstant | <i>&mu;<sub>0</sub></i> | 1.2566370614e-6 | N &#183; A<sup>-2</sup>
343electricConstant | <i>&epsilon;<sub>0</sub></i> | 8.854187817e-12 | F &#183; m<sup>-1</sup>
344vacuumImpedance | <i>Z<sub>0</sub></i> | 376.730313461 | &ohm;
345coulomb | <i>&kappa;</i> | 8.9875517873681764e9 | N &#183; m<sup>2</sup> &#183; C<sup>-2</sup>
346elementaryCharge | <i>e</i> | 1.60217656535e-19 | C
347bohrMagneton | <i>&mu;<sub>B</sub></i> | 9.2740096820e-24 | J &#183; T<sup>-1</sup>
348conductanceQuantum | <i>G<sub>0</sub></i> | 7.748091734625e-5 | S
349inverseConductanceQuantum | <i>G<sub>0</sub><sup>-1</sup></i> | 12906.403721742 | &ohm;
350magneticFluxQuantum | <i><font face="Symbol">f</font><sub>0</sub></i> | 2.06783375846e-15 | Wb
351nuclearMagneton | <i>&mu;<sub>N</sub></i> | 5.0507835311e-27 | J &#183; T<sup>-1</sup>
352klitzing | <i>R<sub>K</sub></i> | 25812.807443484 | &ohm;
353
354<!-- TODO: implement josephson
355josephson | <i>K<sub>J</sub></i> | 4.8359787011e-14 | Hz &#183; V<sup>-1</sup>
356-->
357
358
359#### Atomic and nuclear constants
360
361Name | Symbol | Value | Unit
362------------------------|------------------------------|-----------------------|----------------------------------
363bohrRadius | <i>a<sub>0</sub></i> | 5.291772109217e-11 | m
364classicalElectronRadius | <i>r<sub>e</sub></i> | 2.817940326727e-15 | m
365electronMass | <i>m<sub>e</sub></i> | 9.1093829140e-31 | kg
366fermiCoupling | <i>G<sub>F</sub></i> | 1.1663645e-5 | GeV<sup>-2</sup>
367fineStructure | <i>&alpha;</i> | 7.297352569824e-3 | -
368hartreeEnergy | <i>E<abbr>h</abbr> </i> | 4.3597443419e-18 | J
369protonMass | <i>m<sub>p</sub></i> | 1.67262177774e-27 | kg
370deuteronMass | <i>m<sub>d</sub></i> | 3.3435830926e-27 | kg
371neutronMass | <i>m<sub>n</sub></i> | 1.6749271613e-27 | kg
372quantumOfCirculation | <i>h / (2m<sub>e</sub>)</i> | 3.636947552024e-4 | m<sup>2</sup> &#183; s<sup>-1</sup>
373rydberg | <i>R<sub>&infin;</sub></i> | 10973731.56853955 | m<sup>-1</sup>
374thomsonCrossSection | | 6.65245873413e-29 | m<sup>2</sup>
375weakMixingAngle | | 0.222321 | -
376efimovFactor | | 22.7 | -
377
378
379#### Physico-chemical constants
380
381Name | Symbol | Value | Unit
382--------------------|------------------------------|---------------------|--------------------------------------------
383atomicMass | <i>m<sub>u</sub></i> | 1.66053892173e-27 | kg
384avogadro | <i>N<sub>A</sub></i> | 6.0221412927e23 | mol<sup>-1</sup>
385boltzmann | <i>k</i> | 1.380648813e-23 | J &#183; K<sup>-1</sup>
386faraday | <i>F</i> | 96485.336521 | C &#183; mol<sup>-1</sup>
387firstRadiation | <i>c<sub>1</sub></i> | 3.7417715317e-16 | W &#183; m<sup>2</sup>
388loschmidt | <i>n<sub>0</sub></i> | 2.686780524e25 | m<sup>-3</sup>
389gasConstant | <i>R</i> | 8.314462175 | J &#183; K<sup>-1</sup> &#183; mol<sup>-1</sup>
390molarPlanckConstant | <i>N<sub>A</sub> &#183; h</i>| 3.990312717628e-10| J &#183; s &#183; mol<sup>-1</sup>
391molarVolume | <i>V<sub>m</sub></i> | 2.241396820e-10 | m<sup>3</sup> &#183; mol<sup>-1</sup>
392sackurTetrode | | -1.164870823 | -
393secondRadiation | <i>c<sub>2</sub></i> | 1.438777013e-2 | m &#183; K
394stefanBoltzmann | <i>&sigma;</i> | 5.67037321e-8 | W &#183; m<sup>-2</sup> &#183; K<sup>-4</sup>
395wienDisplacement | <i>b</i> | 2.897772126e-3 | m &#183; K
396
397<!-- TODO: implement spectralRadiance
398spectralRadiance | <i>c<sub>1L</sub></i> | 1.19104286953e-16 | W &#183; m<sup>2</sup> &#183; sr<sup>-1</sup>
399-->
400
401Note that the values of `loschmidt` and `molarVolume` are at `T = 273.15 K` and `p = 101.325 kPa`.
402The value of `sackurTetrode` is at `T = 1 K` and `p = 101.325 kPa`.
403
404
405#### Adopted values
406
407Name | Symbol | Value | Unit
408--------------|------------------------------|---------|-------------------------
409molarMass | <i>M<sub>u</sub></i> | 1e-3 | kg &#183; mol<sup>-1</sup>
410molarMassC12 | <i>M(<sub>12</sub>C)</i> | 1.2e-2 | kg &#183; mol<sup>-1</sup>
411gravity | <i>g<sub>n</sub></i> | 9.80665 | m &#183; s<sup>-2</sup>
412atm | <i>atm</i> | 101325 | Pa
413
414
415#### Natural units
416
417Name | Symbol | Value | Unit
418------------------|-----------------------|--------------------|-----
419planckLength | <i>l<sub>P</sub></i> | 1.61619997e-35 | m
420planckMass | <i>m<sub>P</sub></i> | 2.1765113e-8 | kg
421planckTime | <i>t<sub>P</sub></i> | 5.3910632e-44 | s
422planckCharge | <i>q<sub>P</sub></i> | 1.87554595641e-18 | C
423planckTemperature | <i>T<sub>P</sub></i> | 1.41683385e+32 | K