OpenSCAD User Manual/Mathematical Functions

From Wikibooks, open books for an open world
Jump to: navigation, search

Trigonometric Functions[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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

asin[edit]

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

atan[edit]

Mathematical arctangent, or inverse tangent, function. Returns the principal value of the arc tangent of x, expressed in degrees. See: Inverse trigonometric functions

atan2[edit]

Mathematical two-argument atan function, taking y as its first argument. Returns the principal value of the arc tangent of y/x, expressed in degrees. See: atan2

Other Mathematical Functions[edit]

abs[edit]

Mathematical absolute value function. Returns the positive value of a signed decimal number.

Usage examples:

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

Results:

5.0
0.0
8.0

ceil[edit]

Mathematical ceiling function. ceil(x) is the smallest integer not less than x.

See: Ceil Function

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

concat[edit]

[Note: Requires version 2014.QX(see [1])]

Return a vector containing the arguments.

Where an argument is a vector the elements of the vector are individually added to the result vector. Strings are distinct from vectors in this case.

Usage examples:

echo(concat("a","b","c","d","e","f"));          // produces ECHO: ["a", "b", "c", "d", "e", "f"]
echo(concat(["a","b","c"],["d","e","f"]));      // produces ECHO: ["a", "b", "c", "d", "e", "f"]
echo(concat(1,2,3,4,5,6));                      // produces ECHO: [1, 2, 3, 4, 5, 6]

Vector of vectors

echo(concat([ [1],[2] ], [ [3] ]));             // produces ECHO: [[1], [2], [3]]

Contrast with strings

echo(concat([1,2,3],[4,5,6]));                   // produces ECHO: [1, 2, 3, 4, 5, 6]
echo(concat("abc","def"));                       // produces ECHO: ["abc", "def"]
echo(str("abc","def"));                          // produces ECHO: "abcdef"

cross[edit]

Calculates the cross product of two vectors in 3D space. The result is a vector that is perpendicular to both of the input vectors.

Using invalid input parameters (e.g. vectors with a length different from 3 or other types) will produce an undefined result.

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, 3, 4], "5"));           // produces ECHO: undef

exp[edit]

Mathematical exp function. Returns the base-e exponential function of x, which is the number e raised to the power x. See: Exponent

floor[edit]

Mathematical floor function. floor(x) = is the largest integer not greater than x

See: Floor Function

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

ln[edit]

Mathematical natural logarithm. See: Natural logarithm

len[edit]

Mathematical length function. Returns the length of an array, a vector or a string parameter.

Usage examples:

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

a=6; len_a=len(a);
echo(a,len_a);

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: 6, undef
ECHO: [1, 2, 3, 4, 5, 6, 7, 8], 8
ECHO: [[0, 0], [0, 1], [1, 0], [1, 1]], 4
ECHO: [1, 0], 2


This function allows (e.g.) the parsing of an array, a vector or a string.

Usage examples:

str2="4711";
for (i=[0:len(str2)-1])
        echo(str("digit ",i+1,"  :  ",str2[i]));

Results:

ECHO: "digit 1  :  4"
ECHO: "digit 2  :  7"
ECHO: "digit 3  :  1"
ECHO: "digit 4  :  1"

Note that the len() function is not defined when a simple variable is passed as the parameter.

This is useful when handling parameters to a module, similar to how shapes can be defined as a single number, or as an [x,y,z] vector; i.e. cube(5) or cube([5,5,5])

For example

module doIt(size) {
        if (len(size) == undef) {
                // size is a number, use it for x,y & z. (or could be undef)
                do([size,size,size]);
        } else { 
                // size is a vector, (could be a string but that would be stupid)
                do(size);
        }
 }
 
doIt(5);        // equivalent to [5,5,5]
doIt([5,5,5]);  // similar to cube(5) v's cube([5,5,5])

let[edit]

[Note: Requires version 2014.QX(see [2])]

Sequential assignment of variables inside an expression. The following expression is evaluated in context of the let assignments and can use the variables. This is mainly useful to make complicated expressions more readable by assigning interim results to variables.

Parameters

let (var1 = value1, var2 = f(var1), var3 = g(var1, var2)) expression

Usage Example:

echo(let(a = 135, s = sin(a), c = cos(a)) [ s, c ]); // ECHO: [0.707107, -0.707107]

log[edit]

Mathematical logarithm. See: Logarithm

lookup[edit]

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

Notes
There is a bug where out-of-range keys will 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:
  • Will create a sort of 3D chart made out of cylinders of different height.
 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

max[edit]

Returns the maximum of the parameters. If a single vector is given as parameter, returns the maximum element of that vector.

Parameters

max(n,n{,n}...)
max(vector)
<n> 
Two or more decimals
<vector> 
Single vector of decimals (requires OpenSCAD version 2014.06 or later).

Usage Example:

max(3.0,5.0)
max(8.0,3.0,4.0,5.0)
max([8,3,4,5])

Results:

5
8
8

min[edit]

Returns the minimum of the parameters. If a single vector is given as parameter, returns the minimum element of that vector.

Parameters

min(n,n{,n}...)
min(vector)
<n> 
Two or more decimals
<vector> 
Single vector of decimals (requires OpenSCAD version 2014.06 or later).

Usage Example:

min(3.0,5.0)
min(8.0,3.0,4.0,5.0)
min([8,3,4,5])

Results:

3
3
3



Looking for mod - it's not a function, see modulo operator (%)

norm[edit]

Returns the euclidean norm of a vector. Note this returns is the actual numeric length while len returns the number of elements in the vector or array.

Usage examples:

a=[1,2,3,4];
b="abcd";
c=[];
d="";
e=[[1,2,3,4],[1,2,3],[1,2],[1]];
echo(norm(a)); //5.47723
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: 5.47723
ECHO: undef
ECHO: 0
ECHO: undef
ECHO: 5.47723
ECHO: 3.74166
ECHO: 2.23607
ECHO: 1

pow[edit]

Mathematical power function.

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)); // means 10^2 or 10*10
// result: ECHO: 100

echo(pow(10,3)); // means 10^3 or 10*10*10
// result: ECHO: 1000

echo(pow(125,1/3)); // means 125^(0.333...) which equals calculating the cube root of 125
// result: ECHO: 5

rands[edit]

Random number generator. Generates a constant vector of pseudo random numbers, much like an array. The numbers are doubles not integers. When generating only one number, you still call it with variable[0]

Parameters

min_value 
Minimum value of random number range
max_value 
Maximum value of random number range
value_count 
Number of random numbers to return as a vector
seed_value (optional) 
Seed value for random number generator for repeatable results.

Usage Examples:

// get a single number
single_rand = rands(0,10,1)[0];
echo(single_rand);
// get a vector of 4 numbers
seed=42;
random_vect=rands(5,15,4,seed);
echo( "Random 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: "Random Vector: ", [8.7454, 12.9654, 14.5071, 6.83435]

round[edit]

The "round" operator returns the greatest or least integer part, respectively, if the numeric input is positive or negative.

Some examples:

round(x.5) = x+1.
round(x.49) = x.
round(-(x.5)) = -(x+1).
round(-(x.49)) = -x.

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

sign[edit]

Mathematical signum function. Returns a unit value that extracts the sign of a value see: Signum function

Parameters

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

Usage examples:

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

Results:

-1.0
0.0
1.0


sqrt[edit]

Mathematical square root function.


Usage Examples:

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