Skip to main content

Math in Bitbybit

Math category icon

View Full Source & Details on GitHub

bitbybit.math works on plain numbers. Many of its functions wrap JavaScript's own Math, so that Rete and Blockly can use them as nodes and blocks; in TypeScript you can call either.

Angles are in radians​

sin, cos and tan take an angle in radians, and asin, acos and atan give one. Most angles people type are in degrees, so convert at the boundary with degToRad and radToDeg: 180 degrees is pi(), about 3.14159.

Arithmetic​

  • add, subtract, multiply, divide and power work on first and second, in that order: subtract gives first minus second, power gives first to the power of second. Dividing by 0 gives Infinity, as in JavaScript.
  • modulus gives the remainder of a division; its sign follows the first number, so -7 modulus 3 is -1.
  • twoNrOperation does any of add, subtract, multiply, divide, power or modulus, chosen by operation.
  • abs, negate, sign (-1, 0 or 1), sqrt (NaN for a negative number), ln, log10, exp (e to the power) and tenPow (10 to the power) work on one number.
  • oneNrOperation does any one-number operation, chosen by operation: the ones above, the rounding and trigonometric functions and the angle conversions.
  • evalArithmetic works out an expression typed as text, such as (3 + 2) / 4, with numbers, +, -, *, / and parentheses. The library parses it itself and never runs it as JavaScript, so it is safe with text a user typed. Anything else in the text stops the script with an error.

Rounding and formatting​

  • round rounds to the nearest whole number, with halves rounding up; floor rounds down and ceil rounds up.
  • roundToDecimals rounds to decimalPlaces digits after the point, and a small negative number rounds to 0, never to -0. roundAndRemoveTrailingZeros does the same and also cleans floating-point noise, so 1.320000001 becomes 1.32.
  • fract keeps the part after the decimal point, measured up from the whole number below, so -2.3 gives 0.7.
  • toFixed gives text, not a number, with exactly decimalPlaces digits and trailing zeros kept: 5 with 3 places is "5.000".
  • niceStep rounds a positive number to a step on the 1, 2, 5 scale, the sizes a grid, a ruler or a slider reads well in: 0.1, 0.2, 0.5, 1, 2, 5, 10 and on. direction says which way: up gives the smallest step at or above the number, down the largest at or below it, and nearest the closest by ratio, so 0.37 gives 0.5 up, 0.2 down and 0.5 nearest. A number within a billionth of a step counts as that step, so rounding noise never moves it on. A span divided by the number of ticks wanted, rounded up, gives a grid that fits.

Lengths in other units​

A model's numbers carry no unit of their own. These help when a size arrives in one unit and the model works in another, or when a length has to be written the way a drawing or a catalogue writes it. The units are millimetres, centimetres, metres and inches.

  • convertLength converts value from the unit from to the unit to. The factors are exact, an inch being 25.4 millimetres: 1 inch gives 25.4 millimetres and 250 millimetres gives 0.25 metres.
  • millimetresPerUnit gives how many millimetres one of a unit holds: 25.4 for an inch, 10 for a centimetre, 1000 for a metre. It is the figure a file or a recipe records to say what its numbers are measured in.
  • toFractionText writes a number as inch sizes are written, a whole number and a reduced fraction, rounded to the nearest 1/denominator. With the default denominator of 64, sixty-fourths of an inch, 1.25 gives "1-1/4", 0.375 gives "3/8", 2 gives "2" and -0.5 gives "-1/2"; with denominator 8, 0.3 rounds to the nearest eighth and gives "1/4".

Numbers to start from​

  • number passes a number through unchanged, so a value can be set once in Rete or Blockly, named and reused. pi gives pi.
  • random gives a number from 0 up to, but not including, 1. randomNumber gives one between low and high, and randomNumbers gives count of them. Each call gives new values.

Blending, easing and ranges​

These are the building blocks of animation and parametric variation.

  • lerp blends from start to end by a fraction t: 0 gives the start, 1 the end, and a t outside 0 to 1 continues past them. inverseLerp goes the other way and gives the t of a value.
  • remap maps a number from one range onto another, keeping its relative position: 5 in 0 to 10 becomes 50 in 0 to 100.
  • ease maps x from 0 to 1 onto min to max along an easing curve, so the change speeds up or slows down instead of being even. ease names the curve: an easeIn... curve starts slowly, easeOut... ends slowly and easeInOut... does both, in the Sine, Quad, Cubic, Quart, Quint, Expo, Circ, Elastic, Back and Bounce families.
  • smoothstep turns a value from 0 to 1 into a gentle S-curve, after clamping it to that range.
  • clamp keeps a number between min and max.
  • wrap cycles a number into the range from min up to max, so 370 in 0 to 360 gives 10. Unlike a plain modulus it handles negative numbers.
  • pingPong bounces a growing t back and forth between 0 and length.
  • moveTowards moves current toward target by at most maxDelta, without overshooting.
  • shortestAngle gives the angle to names, whole turns aside, that lies nearest from, so turning from from to it goes the short way round: from 10 to 350 degrees it gives -10, and from 350 to 10 it gives 370. Animating a camera or a dial toward it never spins the long way. fullTurn is 360 for degrees; give two pi for radians.

Here a fraction, as a slider gives it, is remapped to a height between 1 and 6 and rounded to one decimal, and the height sizes a column:

A fraction remapped to a height
Bitbybit Platform

A fraction remapped to a height in Rete

rete logoRete
Script Source (rete)
{
"id": "rete-v2-json",
"nodes": {
"height": {
"id": "height",
"name": "bitbybit.math.remap",
"customName": "remap",
"async": false,
"drawable": false,
"data": {
"genericNodeData": {
"hide": false,
"oneOnOne": false,
"flatten": 0,
"forceExecution": false
},
"number": 0.7,
"fromLow": 0,
"fromHigh": 1,
"toLow": 1,
"toHigh": 6
},
"inputs": {},
"position": [
40,
40
]
},
"rounded": {
"id": "rounded",
"name": "bitbybit.math.roundToDecimals",
"customName": "round to decimals",
"async": false,
"drawable": false,
"data": {
"genericNodeData": {
"hide": false,
"oneOnOne": false,
"flatten": 0,
"forceExecution": false
},
"number": 1.123456,
"decimalPlaces": 1
},
"inputs": {
"number": {
"connections": [
{
"node": "height",
"output": "result",
"data": {}
}
]
}
},
"position": [
460,
40
]
},
"column": {
"id": "column",
"name": "bitbybit.occt.shapes.solid.createCylinder",
"customName": "cylinder",
"async": true,
"drawable": true,
"data": {
"genericNodeData": {
"hide": false,
"oneOnOne": false,
"flatten": 0,
"forceExecution": false
},
"radius": 0.5,
"height": 2,
"center": [
0,
0,
0
],
"direction": [
0,
1,
0
],
"angle": 360,
"originOnCenter": false
},
"inputs": {
"height": {
"connections": [
{
"node": "rounded",
"output": "result",
"data": {}
}
]
}
},
"position": [
880,
40
]
}
},
"modules": {}
}

Every function​

FunctionWhat it does
absDrops the sign of a number, so the result is never negative.
acosFinds the angle, in radians, whose cosine is the given number.
addAdds two numbers.
asinFinds the angle, in radians, whose sine is the given number.
atanFinds the angle, in radians, whose tangent is the given number.
ceilRounds a number up to the whole number above it.
clampKeeps a number within a range: below min becomes min, above max becomes max.
convertLengthConverts a length from one unit to another.
cosFinds the cosine of an angle given in radians.
degToRadConverts an angle from degrees to radians.
divideDivides the first number by the second.
easeMaps a value from 0 to 1 onto the range min to max along an easing curve, so the result speeds up or slows down instead of changing evenly.
evalArithmeticWorks out a simple arithmetic expression written as text: numbers, +, -, the multiplication sign, /, parentheses and spaces.
expRaises e, the base of the natural logarithm, to the power of a number.
floorRounds a number down to the whole number below it.
fractKeeps the part of a number after the decimal point, measured up from the whole number below it, so the result is always from 0 up to 1.
inverseLerpFinds where a value sits between a start and an end, as a fraction: the t that lerp would need to produce it.
lerpBlends from a start value to an end value by a fraction t: 0 gives the start, 1 the end, 0.5 the midpoint.
lnFinds the natural logarithm of a number: the power e must be raised to for that number.
log10Finds the base-10 logarithm of a number: the power 10 must be raised to for that number.
millimetresPerUnitGives how many millimetres one of a unit of length holds.
modulusFinds the remainder after dividing one number by another.
moveTowardsMoves a value toward a target by at most maxDelta, without overshooting it.
multiplyMultiplies two numbers.
negateFlips the sign of a number.
niceStepRounds a positive number to a step on the 1, 2, 5 scale - 0.1, 0.2, 0.5, 1, 2, 5, 10 - the sizes a grid, a ruler or a slider reads well in.
numberPasses a number through unchanged, so a value can be given a name and reused.
oneNrOperationApplies one operation to a single number: absolute, negate, square root, rounding, logarithms, the trigonometric functions and their inverses, exponential, or a conversion between radians and degrees.
piGives the constant pi, the ratio of a circle's circumference to its diameter.
pingPongBounces a value back and forth between 0 and length as t grows: up to length, back down to 0, and again.
powerRaises the first number to the power of the second.
radToDegConverts an angle from radians to degrees.
randomGives a random number from 0 up to, but not including, 1.
randomNumberGives a random number between low and high.
randomNumbersGives a list of random numbers between low and high.
remapMaps a number from one range onto another, keeping its relative position.
roundRounds a number to the nearest whole number; halves round up.
roundAndRemoveTrailingZerosRounds a number to a given number of decimal places and drops the zeros at the end.
roundToDecimalsRounds a number to a given number of decimal places.
shortestAngleGives the angle that to names, whole turns aside, nearest to from, so going from from to it is the short way round.
signTells the sign of a number: -1 when negative, 0 when zero, 1 when positive.
sinFinds the sine of an angle given in radians.
smoothstepTurns a value from 0 to 1 into a smooth S-curve that starts and ends gently; the value is clamped to that range first.
sqrtFinds the square root of a number.
subtractSubtracts the second number from the first.
tanFinds the tangent of an angle given in radians.
tenPowRaises 10 to the power of a number.
toFixedFormats a number as text with a fixed number of decimal places, keeping trailing zeros.
toFractionTextWrites a number as a whole number and a reduced fraction, rounded to the nearest 1/denominator, as inch sizes are written.
twoNrOperationApplies one arithmetic operation to two numbers: add, subtract, multiply, divide, power or modulus.
wrapWraps a number into a range so it cycles round: past max it comes back in at min, and below min it comes back in at max.