Mon. Jan 23rd, 2023

Arithmetic Functions

These are functions built in to (or available as add-ons) most programming languages.


Picks a pseudo-random number.

Random r = new Random(); //Create a random number generator
int x = r.Next(100); //Pick a random number, 0-99

import random 
#You must import the random library

x = rand.randint(0, 100)
#pick a random integer between 0-100


A range represents a set of numbers. This terminology does not apply to C#.

range(10) #Numbers from 0 to 9


Mathematically rounds a number. Generally languages use an ‘away from zero’ method so that negative values are treated the same way as positive values.

Standard mathematical rules are applied: that is any positive number with a fractional part of 0.5 or greater is rounded up, otherwise it is rounded down. For negative numbers, any number with a fractional part of 0.5 or greater is rounded down (e.g. -1.7 becomes -2.0) and below 0.5 is rounded up.

Note that rounding a value is different to integer division or truncation, in which case the fractional part is simply discarded.

float x = 1.53f; 
int j = Math.Round(x);
//Round is a function within the Math library

x = 1.663
y = round(x)
z = round(x,2)
#round used with one argument (y=...) will return whole number : 2
#round used with two arguments returns number to that many places, 1.66


Truncation simply discards any fractional part of a value.

float x = 1.53f;
int y = Math.Truncate(x);
//This will set x to 1. Truncate is part of the Math library

x = 1.53
y = trunc(x)
#This will set y to 1