LessonsBeginner: First stepsLesson 6

Math functions

Rounding, the biggest and smallest of a list, averages, square roots, trigonometry and random numbers.

  • Beginner
  • Lesson 6 of 83
  • About 8 minutes
  • 6 examples

Calling a function

A function takes some values, works something out and gives back the answer. xTalk has hundreds built in. You call one with its name and its values in brackets, separated by commas. A function's answer can go wherever a value can: into put, a variable, a sum, or another function.

ExampleRun it in the playground
put round(3.7)
put round(2.5)
put round(3.14159, 2)
put trunc(9.99)
put abs(-12)
Output
4
3
3.14
9
12

round rounds a half away from zero, as you learnt at school; its second value says how many decimal places to keep. trunc just drops the decimals, and abs drops the minus sign.

Biggest, smallest, total, average

These take any number of values, or one value that is a list separated by commas, which is handy when the numbers are in a variable.

ExampleRun it in the playground
put max(4, 19, 7)
put min(4, 19, 7)
put sum(1, 2, 3, 4)
put "4,8,15,16,23,42" into tNumbers
put average(tNumbers)
put median(tNumbers)
put max(tNumbers) - min(tNumbers)
Output
19
4
10
18
15.5
38

Roots, powers and pi

ExampleRun it in the playground
put sqrt(81)
put 27 ^ (1/3) -- a cube root
put pi
put round(pi * 3 ^ 2, 2) -- the area of a circle of radius 3
Output
9
3
3.141593
28.27

Angles

The trigonometry functions work in radians, where a whole turn is 2 * pi. To use degrees, multiply by pi / 180 on the way in, and by 180 / pi on the way out. They are what you need to move something in a circle, or point it at the mouse.

ExampleRun it in the playground
put sin(pi / 2)
put cos(pi)
put round(sin(30 * pi / 180), 2)
put atan2(1, 1) * 180 / pi
Output
1
-1
0.5
45

Random numbers

random(n) gives a whole number from 1 to n, a different one each time. Games are made of it. any picks something at random from a list. Run this a few times and watch it change:

ExampleRun it in the playground
put "You rolled a" && random(6)
put "Two dice:" && random(6) + random(6)
put "Between 10 and 20:" && random(11) + 9
put "I choose" && any item of "rock,paper,scissors"
Output (yours will differ: it changes from run to run)
You rolled a 4
Two dice: 9
Between 10 and 20: 13
I choose paper

Try it yourself

Five friends' heights in centimetres are 162, 175, 158, 181 and 170. Put the tallest, the shortest, and the average rounded to one decimal place.

Show a solution
ExampleRun it in the playground
put "162,175,158,181,170" into tHeights
put max(tHeights)
put min(tHeights)
put round(average(tHeights), 1)
Output
181
158
169.2

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.