Quantity Math

Great, our first example checks out! But like I mentioned, European scales don't actually read out in Newtons, but in kilograms. Remember the relationship between force and mass from your physics class?

F=ma

Force=mass×acceleration

We know the value of force and want to solve for mass. What would the acceleration be? This is the acceleration due to Earth's gravity. A good way to visualize that number is drop something (light weight, be safe!) and watch it fall. Notice how it speeds up as it falls - the "speed up" is the acceleration. We call this value g. On Earth, g9.81[m/s2] in SI units.

m=Fg

We could convert g to US units, but there's no need, since dimensional will handle all unit conversions internally.

When we divide force by acceleration, the units from force and acceleration will persist. We'll end up with a rather strange unit like this:

lbfms2=lbfs2m

What are the dimensions on this unit? We can run a quick dimensional analysis using Quantity.Unit.Attribute.Dimension.toString() to get a human-readable representation of our physical base dimensions. Believe it or not, the dimension of that unit is just mass! That means, we can convert quantities with that unit to any unit of mass.

From plugging it into an online calculator, I expect the result to be about 68[kg].

Follow these steps to create a new project workspace and install the dimensional dependency to run this example.

# Create and open project folder
mkdir Quantity_Math_demo
cd Quantity_Math_demo
# Initialize project and install dependencies
npm init -y
npm i dimensional@0.4.1
# Create and open source file
touch "Quantity Math.mjs"
open "Quantity Math.mjs"

Copy and paste this source code into Quantity Math.mjs.

import { Q, U } from 'dimensional';

// This is our weight from the previous example
const weight_lbs = Q(150, U({ pound_force: 1 }));

// Define Earth's gravity at sea level in SI units
const gravity = Q(9.81, U({ meter: 1, second: -2 }));

// Remember `F=ma`? Rearrange to `m=F/a`
const mass = weight_lbs.over(gravity);

// The units persist through the operation, unless if they cancel
// So we'll get `lbf*s^2/m` ... which is not the most useful unit
console.log(mass.toString());

// What are the dimensions on this weird unit?
console.log('dim=' + mass.unit.attribute.dimension.toString());

// We can use the Quantity.as(unit) method to convert to kg
console.log(mass.as(U({ kilogram: 1 })).toString());

In Quantity_Math_demo/, execute Quantity Math.mjs with NodeJS to generate an output.

node "Quantity Math.mjs"

You should expect to see an output similar to the one below.

15.29051987767584 \left[\frac{\text{lb}_{f} \cdot \text{s}^{2}}{\text{m}}\right]
dim=\textbf{M}
68.01561029966939 \left[\text{k} \text{g}\right]
MMNEPVFCICPMFPCPTTAAATR