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