Math

This library allows for the calculation of min/max, absolute value and the square root of a number. Users can also constrain a number within a range, re-map a number from one range to another, and calculate the value of a number raised to a power.

min

Description

Calculates the minimum of two numbers.

Syntax

min(x, y)

Parameters

x: The first number, any data type
y: The second number, any data type

Returns

The smaller of the two numbers.

max

Description

Calculates the maximum of two numbers.

Syntax

max(x, y)

Parameters

x: The first number, any data type
y: The second number, any data type

Returns

The larger of the two parameter values.

abs

Description

Computes the absolute value of a number.

Syntax

abs(x)

Parameters

x: The number

Returns

If x is greater than or equal to 0. -x: If x is less than 0.

constrain

Description

Constrains a number to be within a range.

Syntax

constrain(x, a, b)

Parameters

x: The number to constrain, all data types
a: The lower end of the range, all data types
b: The upper end of the range, all data types

Returns

x: If x is between a and b. a: If x is less than a. b: If x is greater than b.

map

Description

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Syntax

map(value, fromLow, fromHigh, toLow, toHigh)

Parameters

value: The number to map
fromLow: The lower bound of the value's current range
fromHigh: The upper bound of the value's current range
toLow: The lower bound of the value's target range
toHigh: The upper bound of the value's target range

Returns

The mapped value.

pow

Description

Calculates the value of a number raised to a power.

Syntax

pow(base, exponent)

Parameters

base: The number (float)
exponent: The power to which the base is raised (float)

Returns

The result of the exponentiation (double)

sqrt

Description

Calculates the square root of a number.

Syntax

sqrt(x)

Parameters

x: The number, any data type

Returns

Double, the number's square root.


Example

Output a calculation with constrain() and pow().


        #include <Arduino.h>
        void setup(){
            Serial.begin(9600);
        }
            
        void loop(){
            Serial.println("Calculate the area of a circle ");
            Serial.println("Input value 0-9");
            while(!Serial.available());
                
            int d = Serial.read();
                
            d = constrain(d - 0x30, 0, 9); //convert from ASCII to numeric, and remove error value
            Serial.print(d);
            Serial.print(" x ");
            Serial.print(d);
            Serial.print(" x 3.14 = ");
            
            Serial.println(pow(d, 2) * PI);
        }