OpenSCAD User Manual/Mathematical Functions

part of Built-in Functions page

Miscellaneous Functions

concat

[Note: Requires version 2015.03]

Concatenation function. Combine the given arguments, in the order given, to make a vector.

Input vectors are reduced to their elements in the new vector so if a given vector should be retained in the result it needs to be wrapped in square brackets ("[]").

Usage examples:

concat( 1, "string", [ 1,2], ["abc","def"])
// ECHO: [1, "string", 1, 2, "abc", "def"], ["xxx", "yyy"]
concat( [["xxx", "yyy"]], [[1,2,3]] )
// ECHO: [["xxx", "yyy"], [1, 2, 3]]

len

Length function. Returns the length of a given vector or string. Returns undef given any other type of input, and emits a warning.

Usage examples:

str1="abcdef"; len_str1=len(str1);
echo(str1,len_str1);

array1=[1,2,3,4,5,6,7,8]; len_array1=len(array1);
echo(array1,len_array1);

array2=[[0,0],[0,1],[1,0],[1,1]]; len_array2=len(array2);
echo(array2,len_array2);

len_array2_2=len(array2[2]);
echo(array2[2],len_array2_2);

Results:

ECHO: "abcdef", 6
ECHO: [1, 2, 3, 4, 5, 6, 7, 8], 8
ECHO: [[0, 0], [0, 1], [1, 0], [1, 1]], 4
ECHO: [1, 0], 2

Only data structures have a length:

echo( len(6) );
// WARNING: len() parameter could not be converted ...
ECHO: undef

let Module

[Note: Requires version 2015.03]

Sequential definition of temporary variables that will be local in the scope of an expression following the let().

Module Form

let( var1 = <expression>, var2 = f(<args>)) x = var1 * var2;

Usage example:

x = let(var1=23,var2=45) var1 * var2;
echo( var1, var2, x );
//WARNING: Ignoring unknown variable "var1" in file ., line 2
//WARNING: Ignoring unknown variable "var2" in file ., line 2
//ECHO: undef, undef, 1035

Let can also be used to create local variables in a Function, or in the body of a for statement.

lookup

Look up value in table, and linearly interpolate if there's no exact match. The first argument is the value to look up. The second is the lookup table -- a vector of key-value pairs.

Parameters

key
A lookup key
<key,value> array
keys and values

There is a bug in which out-of-range keys return the first value in the list. Newer versions of Openscad should use the top or bottom end of the table as appropriate instead.

Usage example: Create a 3D chart made from cylinders of different heights.

 function get_cylinder_h(p) = lookup(p, [
 		[ -200, 5 ],
 		[ -50, 20 ],
 		[ -20, 18 ],
 		[ +80, 25 ],
 		[ +150, 2 ]
 	]);
 
 for (i = [-100:5:+100]) {
 	// echo(i, get_cylinder_h(i));
 	translate([ i, 0, -30 ]) cylinder(r1 = 6, r2 = 2, h = get_cylinder_h(i)*3);
 }
OpenSCAD Lookup Function

Generator Functions

rands

Generates a vector of pseudo random numbers greater than, or equal to, the given minimum and less than the maximum floating point values. The values in the vector will have a fractional component.

Parameters

1) min_value
Required float. Minimum value of random number range
2) max_value
Required float. Maximum value of random number range
3) value_count
Required integer. Quantity of numbers to generate. Value taken as floor( value_count ) to remove fraction.
seed_value
Optional float. Seed value for random number generator for repeatable results. On versions before late 2015, seed_value gets rounded to the nearest integer.

Usage examples

// a single random number
single_rand = rands(0,10,1)[0];
echo(single_rand);
// a vector of 4 numbers between 5 and 15
seed=42;
random_vect=rands(5,15,4,seed);
echo( "Vector: ",random_vect);
sphere(r=5);
for(i=[0:3]) {
 rotate(360*i/4) {
   translate([10+random_vect[i],0,0])
     sphere(r=random_vect[i]/2);
 }
}
// ECHO: "Vector: ", [8.7454, 12.9654, 14.5071, 6.83435]

To obtain random integers between 1 and 10 inclusive we note that rands(1,10,...) only spans 9 values so the results will be mostly fractional. To properly generate integer values in the desired range the parameters should be set to generate right number of intervals.

function irands(minimum, maximum, n) =
    let(floats = rands(minimum, maximum+1, n))
    [ for (f = floats) floor(f) ];
echo(irands(1, 10, 5));
// ECHO: [9, 6, 2, 4, 1]

Mathematical Functions

abs

Mathematical absolute value function. Returns the positive value of the given number.

Usage examples:

abs(-5.0);  returns 5.0
abs(0);     returns 0.0
abs(8.0);   returns 8.0

ceil

Mathematical ceiling function. Returns the next largest integer value as described elsewhere.

Usage examples:

echo(ceil(4.4),ceil(-4.4));     // produces ECHO: 5, -4

cross

Calculates the cross product of two vectors. Both vectors must be the same length, with either three or two values, or the function returns undef.

The cross product of 3D vectors is a vector that is perpendicular to its inputs.

With 2D vectors the cross product can only have a value in the third position of the vector, [0,0,z] which is its determinant. In this case the cross() function returns just the determinant value, the z value of the vector:

cross([x,y,z], [u,v,w]) --> [ x*v, y*u, z*w ]
cross([x,y], [u,v]) --> x*v - y*u --> d 

For any two vectors, 2D or 3D, the following holds for vectors a and b:

cross(a,b) == -cross(b,a)

Usage examples:

echo(cross([2, 3, 4], [5, 6, 7]));     // produces ECHO: [-3, 6, -3]
echo(cross([2, 1, -3], [0, 4, 5]));    // produces ECHO: [17, -10, 8]
echo(cross([2, 1], [0, 4]));           // produces ECHO: 8
echo(cross([1, -3], [4, 5]));          // produces ECHO: 17
echo(cross([2, 1, -3], [4, 5]));       // produces ECHO: undef

exp

Mathematical exponent function using base e. Returns ex, the exponential function of x,

echo(exp(1),exp(ln(3)*4));    // produces ECHO: 2.71828, 81

floor

Mathematical floor function. Returns the integer equal to, or smaller than the given value, as described elsewhere

echo(floor(4.4),floor(-4.4));    // produces ECHO: 4, -5

ln

The mathematical natural logarithm of x is the power to which e would have to be raised to equal x. Normally written as ln x or, to make the base e explicit, loge x as explained in Natural logarithm

log

Base-10 logarithm of a number. The mathematical logarithm of a number is the exponent by which another fixed value, the base, must be raised to produce that number; see w:Logarithm.

y = log(1000); // returns 3, because 103 = 1000

max

Returns the maximum of the parameters. Given a single vector the function returns the element with the maximum value. Any other data type emits a warning and returns undef.

Function's Forms

max(n{,n}*)
one or more floating values
max( [n{,n}*] )
a single vector of one or more floating values

Usage example:

max(3.0,5.0);   // 5.0
max(-11,-22);   // -11
max([8,3,4,5]); // 8

min

Returns the minimum of the parameters. Given a single vector the function returns the element with the minimum value.

Function's Forms

min(n{,n}*)
one or more floating values
min( [n{,n}*] )
a single vector of one or more floating values

Usage example:

min(3.0,5.0);   // 3.0
min(-11,-22);   // -22
min([8,3,4,5]); // 3

mod

The modulo operation is implemented as an operator that takes two arguments, as described in the section on the modulo operator (%).

It is mentioned here to make clear that OpenSCAD does not provide a mod() function,

norm

Returns the Euclidean norm of a vector:

This returns the actual numeric length while len() returns the number of elements in the vector or array.

Usage examples:

a=[1,2,3,4,5,6];
b="abcd";
c=[];
d="";
e=[[1,2,3,4],[1,2,3],[1,2],[1]];
echo(norm(a)); //9.53939
echo(norm(b)); //undef
echo(norm(c)); //0
echo(norm(d)); //undef
echo(norm(e[0])); //5.47723
echo(norm(e[1])); //3.74166
echo(norm(e[2])); //2.23607
echo(norm(e[3])); //1

Results:

ECHO: 9.53939
ECHO: undef
ECHO: 0
ECHO: undef
ECHO: 5.47723
ECHO: 3.74166
ECHO: 2.23607
ECHO: 1

pow

Mathematical power function that raises the base to the power of the exponent.

As of version 2021.01 you can use the exponentiation operator ^ instead.

Parameters

<base>
Decimal. Base.
<exponent>
Decimal. Exponent.

Usage examples:

for (i = [0:5]) {
 translate([i*25,0,0]) {
   cylinder(h = pow(2,i)*5, r=10);
   echo (i, pow(2,i));
 }
}
echo(pow(10,2)); // 10^2 or 10*10
// result: ECHO: 100

echo(pow(10,3)); // 10^3 or 10*10*10
// result: ECHO: 1000
echo(pow(125,1/3)); // means 125^(0.333...), the cube root of 125
// result: ECHO: 5

round

The round function returns the integer value of given .

Usage examples:

round(5.4);  //  5
round(5.5);  //  5
round(5.6);  //  6
round(-5.4); // -5
round(-5.5); // -6
round(-5.6); // -6

Rounding to the nearest value v involves multiplying the argument of round() by 1/v and dividing the result of round() by 1/v. For example, round(x/6)*6 rounds the value x to the nearest multiple of 6, round(x*10)/10 rounds the value x to the nearest multiple of 0.1.

sign

Mathematical sign function. Returns a signed unit value, thus one (1), with the same sign as the given value, or zero (0) when the input is zero, as explained elsewhere

Parameters

<x>
Decimal. Value to find the sign of.

Usage examples:

sign(-5.0);   // -1
sign(0);      //  0
sign(8.0);    //  1

sqrt

Mathematical square root function.

Usage example
translate([sqrt(100),0,0])sphere(100);


String Functions

str

Convert all arguments to strings and concatenate.

Usage examples:

number=2;
echo ("This is ",number,3," and that's it.");
echo (str("This is ",number,3," and that's it."));

Results:

ECHO: "This is ", 2, 3, " and that's it."
ECHO: "This is 23 and that's it."

This can be used for simple conversion of numbers to strings

s = str(n); 

chr

[Note: Requires version 2015.03]

Convert numbers to a string containing character with the corresponding code. OpenSCAD uses Unicode, so the number is interpreted as Unicode code point. Numbers outside the valid code point range produce an empty string.

Parameters

chr(Number)
Convert one code point to a string of length 1 (number of bytes depending on UTF-8 encoding) if the code point is valid.
chr(Vector)
Convert all code points given in the argument vector to a string.
chr(Range)
Convert all code points produced by the range argument to a string.

Examples

echo(chr(65), chr(97));      // ECHO: "A", "a"
echo(chr(65, 97));           // ECHO: "Aa"
echo(chr([66, 98]));         // ECHO: "Bb"
echo(chr([97 : 2 : 102]));   // ECHO: "ace"
echo(chr(-3));               // ECHO: ""
echo(chr(9786), chr(9788));  // ECHO: "☺", "☼"
echo(len(chr(9788)));        // ECHO: 1

Note: When used with echo() the output to the console for character codes greater than 127 is platform dependent.

ord

[Note: Requires version 2019.05]

Convert a character to a number representing the Unicode code point. If the parameter is not a string, the ord() returns undef.

Parameters

ord(String)
Convert the first character of the given string to a Unicode code point.

Examples

echo(ord("a"));
// ECHO: 97

echo(ord("BCD"));
// ECHO: 66

echo([for (c = "Hello! 🙂") ord(c)]);
// ECHO: [72, 101, 108, 108, 111, 33, 32, 128578]

txt="1";
echo(ord(txt)-48,txt);
// ECHO: 1,"1" // only converts 1 character

len

returns the number of characters in a text.

echo(len("Hello world"));    // 11

See Also search()

search() for text searching.

is_string( <variable> )

The function is_string(value) return true if the value is a string, false else

echo(is_string("alpha")); //true
echo(is_string(22)); //false

Trigonometric functions

The trig functions use the C Language mathematics functions, which are based in turn on Binary Floating Point mathematics, which use approximations of Real Numbers during calculation. OpenSCAD's math functions use the C++ 'double' type, inside Value.h/Value.cc,

A good resource for the specifics of the C library math functions, such as valid inputs/output ranges, can be found at the Open Group website math.h & acos

cos

Mathematical cosine function of degrees. See Cosine

Parameters

<degrees>
Decimal. Angle in degrees.
Usage example:
 for(i=[0:36])
    translate([i*10,0,0])
       cylinder(r=5,h=cos(i*10)*50+60);
OpenSCAD Cos Function‎

sin

Mathematical sine function. See Sine

Parameters

<degrees>
Decimal. Angle in degrees.
Usage example 1:
 for (i = [0:5]) {
  echo(360*i/6, sin(360*i/6)*80, cos(360*i/6)*80);
   translate([sin(360*i/6)*80, cos(360*i/6)*80, 0 ])
    cylinder(h = 200, r=10);
 }
Usage example 2:
 for(i=[0:36])
    translate([i*10,0,0])
       cylinder(r=5,h=sin(i*10)*50+60);
OpenSCAD Sin Function

tan

Mathematical tangent function. See Tangent

Parameters

<degrees>
Decimal. Angle in degrees.
Usage example:
 for (i = [0:5]) {
  echo(360*i/6, tan(360*i/6)*80);
   translate([tan(360*i/6)*80, 0, 0 ])
    cylinder(h = 200, r=10);
 }

acos

Mathematical arccosine, or inverse cosine, expressed in degrees. See: Inverse trigonometric functions

asin

Mathematical arcsine, or inverse sine, expressed in degrees. See: Inverse trigonometric functions

atan

Mathematical arctangent, or inverse tangent, function. Returns the principal value of the arc tangent of x, expressed in degrees. atan cannot distinguish between y/x and -y/-x and returns angles from -90 to +90. See: atan2 and also Inverse trigonometric functions

atan2

Mathematical two-argument atan function atan2(y,x) that spans the full 360 degrees. This function returns the full angle between the x axis and the vector(x,y) expressed in degrees, in the range .

Usage examples:

atan2(5.0,-5.0);     //result: 135 degrees. atan() would give -45
atan2(y,x);          //angle between (1,0) and (x,y) = angle around z-axis