How to use the mathjs.unit function in mathjs

To help you get started, we’ve selected a few mathjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github josdejong / mathjs / examples / units.js View on Github external
// units can be created by providing a value and unit name, or by providing
// a string with a valued unit.
console.log('create units')
const a = math.unit(45, 'cm')
const b = math.unit('0.1m')
print(a) // 45 cm
print(b) // 0.1 m
console.log()

// units can be added, subtracted, and multiplied or divided by numbers and by other units
console.log('perform operations')
print(math.add(a, b)) // 55 cm
print(math.multiply(b, 2)) // 0.2 m
print(math.divide(math.unit('1 m'), math.unit('1 s'))) // 1 m / s
print(math.pow(math.unit('12 in'), 3)) // 1728 in^3
console.log()

// units can be converted to a specific type, or to a number
console.log('convert to another type or to a number')
print(b.to('cm')) // 10 cm  Alternatively: math.to(b, 'cm')
print(math.to(b, 'inch')) // 3.9370078740157 inch
print(b.toNumber('cm')) // 10
print(math.number(b, 'cm')) // 10
console.log()

// the expression parser supports units too
console.log('parse expressions')
print(math.eval('2 inch to cm')) // 5.08 cm
print(math.eval('cos(45 deg)')) // 0.70710678118655
print(math.eval('90 km/h to m/s')) // 25 m / s
console.log()
github josdejong / mathjs / examples / units.js View on Github external
// convert a unit to a number
// A second parameter with the unit for the exported number must be provided
print(math.eval('number(5 cm, mm)')) // number, 50
console.log()

// simplify units
console.log('simplify units')
print(math.eval('100000 N / m^2')) // 100 kPa
print(math.eval('9.81 m/s^2 * 100 kg * 40 m')) // 39.24 kJ
console.log()

// example engineering calculations
console.log('compute molar volume of ideal gas at 65 Fahrenheit, 14.7 psi in L/mol')
const Rg = math.unit('8.314 N m / (mol K)')
const T = math.unit('65 degF')
const P = math.unit('14.7 psi')
const v = math.divide(math.multiply(Rg, T), P)
console.log('gas constant (Rg) = ', format(Rg))
console.log('P = ' + format(P))
console.log('T = ' + format(T))
console.log('v = Rg * T / P = ' + format(math.to(v, 'L/mol')))
// 23.910432393453 L / mol
console.log()

console.log('compute speed of fluid flowing out of hole in a container')
const g = math.unit('9.81 m / s^2')
const h = math.unit('1 m')
const v2 = math.pow(math.multiply(2, math.multiply(g, h)), 0.5) // Can also use math.sqrt
console.log('g = ' + format(g))
console.log('h = ' + format(h))
console.log('v = (2 g h) ^ 0.5 = ' + format(v2))
github gkjohnson / webgl-gpu-power-estimation / scripts / fetch-techpowerup-specs.js View on Github external
parsedTmus,
                parsedRops,
            ] = shadersTmusRops.split(/[\\/]/g).map(s => parseInt(s));

        } catch (e) {

            console.error(e);
            console.error(`${ name }, ${ shadersTmusRops }`);
            console.error('');

        }

        // parse clock speed
        let parsedClock = null;
        try {
            parsedClock = math.unit(clock).toNumber('MHz');
        } catch (e) {
            console.error(e);
            console.error(`${ name }, ${ clock }`);
            console.error('');
        }

        // parse memory clock speed
        let parsedMemoryClock = null;
        try {
            parsedMemoryClock = math.unit(memoryClock).toNumber('MHz');
        } catch (e) {
            console.error(e);
            console.error(`${ name }, ${ memoryClock }`);
            console.error('');
        }
github josdejong / mathjs / examples / units.js View on Github external
// convert a unit to a number
// A second parameter with the unit for the exported number must be provided
print(math.eval('number(5 cm, mm)')) // number, 50
console.log()

// simplify units
console.log('simplify units')
print(math.eval('100000 N / m^2')) // 100 kPa
print(math.eval('9.81 m/s^2 * 100 kg * 40 m')) // 39.24 kJ
console.log()

// example engineering calculations
console.log('compute molar volume of ideal gas at 65 Fahrenheit, 14.7 psi in L/mol')
const Rg = math.unit('8.314 N m / (mol K)')
const T = math.unit('65 degF')
const P = math.unit('14.7 psi')
const v = math.divide(math.multiply(Rg, T), P)
console.log('gas constant (Rg) = ', format(Rg))
console.log('P = ' + format(P))
console.log('T = ' + format(T))
console.log('v = Rg * T / P = ' + format(math.to(v, 'L/mol')))
// 23.910432393453 L / mol
console.log()

console.log('compute speed of fluid flowing out of hole in a container')
const g = math.unit('9.81 m / s^2')
const h = math.unit('1 m')
const v2 = math.pow(math.multiply(2, math.multiply(g, h)), 0.5) // Can also use math.sqrt
console.log('g = ' + format(g))
console.log('h = ' + format(h))
console.log('v = (2 g h) ^ 0.5 = ' + format(v2))
// 4.42944691807 m / s
github josdejong / mathjs / examples / units.js View on Github external
// example engineering calculations
console.log('compute molar volume of ideal gas at 65 Fahrenheit, 14.7 psi in L/mol')
const Rg = math.unit('8.314 N m / (mol K)')
const T = math.unit('65 degF')
const P = math.unit('14.7 psi')
const v = math.divide(math.multiply(Rg, T), P)
console.log('gas constant (Rg) = ', format(Rg))
console.log('P = ' + format(P))
console.log('T = ' + format(T))
console.log('v = Rg * T / P = ' + format(math.to(v, 'L/mol')))
// 23.910432393453 L / mol
console.log()

console.log('compute speed of fluid flowing out of hole in a container')
const g = math.unit('9.81 m / s^2')
const h = math.unit('1 m')
const v2 = math.pow(math.multiply(2, math.multiply(g, h)), 0.5) // Can also use math.sqrt
console.log('g = ' + format(g))
console.log('h = ' + format(h))
console.log('v = (2 g h) ^ 0.5 = ' + format(v2))
// 4.42944691807 m / s
console.log()

console.log('electrical power consumption:')
const expr1 = '460 V * 20 A * 30 days to kWh'
console.log(expr1 + ' = ' + math.eval(expr1)) // 6624 kWh
console.log()

console.log('circuit design:')
const expr2 = '24 V / (6 mA)'
console.log(expr2 + ' = ' + math.eval(expr2)) // 4 kohm
console.log()
github gkjohnson / webgl-gpu-power-estimation / scripts / fetch-videocard-benchmark.js View on Github external
tdp,
            type,

            memory,
            clock,
            memoryClock,

        } = data[name];

        // Memory string can be shaped like "256 MB"
        // Math.js uses `MiB` to do power of 2 megabyte conversions
        const cleanedMemory = memory.replace(/,/g, '').replace(/([A-Z])B/g, (match, scale) => `${ scale }iB`);

        // Parse the numeric values
        const parsedTdp = tdp === 'NA' ? null : parseFloat(tdp);
        const parsedMemory = memory === 'NA' ? null : math.unit(cleanedMemory).toNumber('MiB');
        const cleanClock = clock.replace(/,/g, '');
        let parsedClock;

        // If the clock values have a space, dash or slash between them then
        // convert to an average of the two numbers
        const re = /(\d+)[\s-/]+(\d+)/;
        if (re.test(cleanClock)) {

            const unit = cleanClock.replace(re, '').trim();
            const matches = re.exec(cleanClock);
            const val = (parseFloat(matches[1]) + parseFloat(matches[2])) / 2;
            parsedClock = math.unit(val, unit).toNumber('MHz');

        } else {

            try {
github kalisio / krawler / src / utils.js View on Github external
date = (units.from ? moment.utc(value, units.from) : moment.utc(value))
          } else {
            date = (units.from ? moment(value, units.from) : moment(value))
          }
          // In this case we'd like to reformat as a string
          // otherwise the moment object is converted to standard JS Date
          if (units.to) {
            date = date.format(units.to)
          } else {
            date = date.toDate()
          }
          _.set(object, path, date)
        } else if (units.asString) { // Handle string conversion
          _.set(object, path, value.toString(units.asString))
        } else { // Handle numbers
          _.set(object, path, math.unit(value, units.from).toNumber(units.to))
        }
      }
    })
  })
github oppia / oppia / extensions / interactions / NumberWithUnits / directives / number-with-units-validation.service.ts View on Github external
var earlierInput = this.unitObjectFactory.fromDict(
        earlierRule.inputs.f);
      var laterInput = this.unitObjectFactory.fromDict(
        laterRule.inputs.f);
      if (earlierInput.type === 'fraction') {
        earlierInput.type = 'real';
        earlierInput.real = earlierInput.fraction.toFloat();
      }
      if (laterInput.type === 'fraction') {
        laterInput.type = 'real';
        laterInput.real = laterInput.fraction.toFloat();
      }
      var earlierInputString = earlierInput.toMathjsCompatibleString();
      var laterInputString = laterInput.toMathjsCompatibleString();
      try {
        return math.unit(laterInputString).equals(math.unit(
          earlierInputString));
      } catch (e) {
        var additionalInfo = (
          '\nlaterInput: ' + JSON.stringify(laterInput.toDict()) +
          '\nearlierInput: ' + JSON.stringify(earlierInput.toDict())
        );
        e.message += additionalInfo;
        throw e;
      }
    };
github Bluegrass-Grief-Owls / coordin-eat / server / midpointAlgorithm / mockGetTravelTime.js View on Github external
inCircle.forEach((num, idx) => {
		const deg = 360/ num
		const fuzzRate = .2
		for (let p = 0; p < num; p++){
			const newCoord = [
				center[0] + chance.normal({mean: 1, dev: fuzzRate}) * radii[idx] * math.sin(math.unit(p*deg, 'deg')),
				center[1] + chance.normal({mean: 1, dev: fuzzRate}) * radii[idx] * math.cos(math.unit(p*deg, 'deg'))
			]
			result.push(newCoord)
		}
	})
	return result
github oppia / oppia / core / templates / dev / head / domain / objects / UnitsObjectFactory.ts View on Github external
fromRawInputString(units: any): Units {
    try {
      this.createCurrencyUnits();
    } catch (parsingError) {}

    var compatibleUnits = this.toMathjsCompatibleString(units);
    if (compatibleUnits !== '') {
      try {
        math.unit(compatibleUnits);
      } catch (err) {
        throw new Error(err);
      }
    }
    return new Units(this.fromStringToList(units));
  }
}

mathjs

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif

Apache-2.0
Latest version published 8 days ago

Package Health Score

92 / 100
Full package analysis