Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Numbers

The everyday numeric functions are built in and need no import: absolute value, square root, trigonometry, logarithms, rounding toward a whole number. Two of them round in a direction their names do not announce, and that is what to watch for.

'' The built-in numeric functions need no import.
print "abs( -3.5 ) ="; abs( -3.5 ); ", sgn( -2 ) ="; sgn( -2 )
print "sqr( 2 )    ="; sqr( 2 )
print "exp( 1 )    ="; exp( 1 )
print "log( 100 )  ="; log( 100 ); "  (natural log)"

'' Trigonometry works in radians.
dim as float64 pi = atn( 1 ) * 4
print "pi          ="; pi
print "sin( pi / 6 ) ="; sin( pi / 6 )
print "atan2( 1, 1 ) ="; atan2( 1, 1 )

'' int rounds down, fix rounds toward zero, frac is what fix drops.
print "int( -2.5 ) ="; int( -2.5 ); ", fix( -2.5 ) ="; fix( -2.5 ); _
      ", frac( -2.5 ) ="; frac( -2.5 )

'' / divides as floating point; \ divides whole numbers.
print "7 / 2 ="; 7 / 2; ", 7 \ 2 ="; 7 \ 2; ", 7 mod 2 ="; 7 mod 2

'' mod and \ truncate: the remainder takes the sign of the left side.
print "-7 mod 3 ="; -7 mod 3; ", -7 \ 3 ="; -7 \ 3

'' ^ raises to a power, in floating point.
print "2 ^ 10 ="; 2 ^ 10; ", 2 ^ 0.5 ="; 2 ^ 0.5

Output

abs( -3.5 ) = 3.5, sgn( -2 ) =-1
sqr( 2 )    = 1.414213562373095
exp( 1 )    = 2.718281828459045
log( 100 )  = 4.605170185988092  (natural log)
pi          = 3.141592653589793
sin( pi / 6 ) = 0.4999999999999999
atan2( 1, 1 ) = 0.7853981633974483
int( -2.5 ) =-3, fix( -2.5 ) =-2, frac( -2.5 ) =-0.5
7 / 2 = 3.5, 7 \ 2 = 3, 7 mod 2 = 1
-7 mod 3 =-1, -7 \ 3 =-2
2 ^ 10 = 1024, 2 ^ 0.5 = 1.414213562373095
FunctionGives
abs( x ), sgn( x )the magnitude; -1, 0 or 1
sqr( x )the square root
exp( x ), log( x )e to the power x, and the natural logarithm
sin, cos, tan, asin, acos, atn, atan2trigonometry, in radians
int( x )the largest whole number not above x: it rounds down
fix( x ), frac( x )the whole part toward zero, and what is left

int( -2.5 ) is -3, because int is a floor; code that uses it believing it truncates is wrong for every negative number. fix is the one that truncates.

/ always divides as floating point. \ divides whole numbers and mod gives the remainder; both truncate toward zero, so the remainder takes the sign of the left-hand side and -7 mod 3 is -1. ^ raises to a power, working in float64.

sin( pi / 6 ) prints 0.4999999999999999 rather than 0.5: pi holds the nearest float64 to pi, not pi itself. Results from the square root, logarithms and trigonometry come from each platform's maths library.

The std/numeric module fills the gaps: rounding that names its direction, exact integer arithmetic, overflow control, and more. The pages that follow use it.

Activities

  1. Print int( 2.7 ), int( -2.7 ), fix( 2.7 ) and fix( -2.7 ), and predict each before you run it.
  2. Convert 90 degrees to radians and print its sine.