Sat. Jan 21st, 2023

Arithmetic Functions

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

Random

Picks a pseudo-random number.

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


Python
import random 
#You must import the random library

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

Range

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

Python
range(10) #Numbers from 0 to 9

Round

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.

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


Python
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

Truncation simply discards any fractional part of a value.

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


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