# Math Library (mathlib)
# Difficulty: 1
# Description: Examples of using the Math Library in Razen
## Introduction
The Math Library (`mathlib`) provides mathematical functions and constants for numerical operations in Razen. This library includes basic arithmetic, trigonometry, logarithms, and other common mathematical operations.
## Library Overview
### Math Library Functions
- `add` → Adds two numbers
- `subtract` → Subtracts the second number from the first (Note: corrected from "subtrack" in the documentation)
- `multiply` → Multiplies two numbers
- `divide` → Divides the first number by the second
- `power` → Raises a number to a specified power
- `sqrt` → Calculates the square root of a number
- `abs` → Returns the absolute value of a number
- `round` → Rounds a number to the nearest integer
- `floor` → Rounds a number down to the nearest integer
- `ceil` → Rounds a number up to the nearest integer
- `sin`, `cos`, `tan` → Trigonometric functions (angles in radians)
- `log` → Calculates the logarithm of a number with a specified base
- `exp` → Calculates e raised to the power of a number
- `random` → Generates a random number between 0 and 1
- `max` → Returns the largest of the provided numbers
- `min` → Returns the smallest of the provided numbers
- `modulo` → Returns the remainder of a division
### Math Constants
- `PI` → The mathematical constant π (3.141592...)
- `E` → The mathematical constant e (2.718281...)
## How to Use the Math Library
### Library Import
To use the Math Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib mathlib;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
mathlib::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
mathlib[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Basic Arithmetic Operations
```razen
# Import the math library
lib mathlib;
# Addition
num sum = mathlib::add(5, 3);
show "5 + 3 = " + sum; # Output: 8
# Subtraction
num difference = mathlib::subtract(10, 4);
show "10 - 4 = " + difference; # Output: 6
# Multiplication
num product = mathlib::multiply(6, 7);
show "6 * 7 = " + product; # Output: 42
# Division
num quotient = mathlib::divide(15, 3);
show "15 / 3 = " + quotient; # Output: 5
# Division with decimal result
num decimalResult = mathlib::divide(10, 4);
show "10 / 4 = " + decimalResult; # Output: 2.5
```
### Power and Roots
```razen
# Import the math library
lib mathlib;
# Power
num power = mathlib::power(2, 8);
show "2^8 = " + power; # Output: 256
# Square root
num sqrt = mathlib::sqrt(25);
show "√25 = " + sqrt; # Output: 5
# Using power for roots (cube root of 27)
num cubeRoot = mathlib::power(27, mathlib::divide(1, 3));
show "Cube root of 27 = " + cubeRoot; # Approximately 3
```
### Rounding Numbers
```razen
# Import the math library
lib mathlib;
# Round to nearest integer
num rounded = mathlib::round(3.7);
show "round(3.7) = " + rounded; # Output: 4
# Floor (round down)
num floored = mathlib::floor(3.7);
show "floor(3.7) = " + floored; # Output: 3
# Ceiling (round up)
num ceiling = mathlib::ceil(3.2);
show "ceil(3.2) = " + ceiling; # Output: 4
```
### Absolute Value
```razen
# Import the math library
lib mathlib;
# Absolute value
num absolute = mathlib::abs(-42);
show "abs(-42) = " + absolute; # Output: 42
# Absolute value of a positive number
show "abs(42) = " + mathlib::abs(42); # Output: 42
```
### Trigonometric Functions
```razen
# Import the math library
lib mathlib;
# Convert degrees to radians
fun toRadians(num degrees) {
return mathlib::multiply(degrees, mathlib::divide(mathlib::PI, 180));
}
# Calculate sine of 30 degrees
num sin30 = mathlib::sin(toRadians(30));
show "sin(30°) = " + sin30; # Output: 0.5
# Calculate cosine of 60 degrees
num cos60 = mathlib::cos(toRadians(60));
show "cos(60°) = " + cos60; # Output: 0.5
# Calculate tangent of 45 degrees
num tan45 = mathlib::tan(toRadians(45));
show "tan(45°) = " + tan45; # Approximately 1
```
### Logarithms and Exponentials
```razen
# Import the math library
lib mathlib;
# Natural logarithm (base e)
num ln = mathlib::log(mathlib::E, mathlib::E);
show "ln(e) = " + ln; # Output: 1
# Logarithm base 10
num log100 = mathlib::log(100, 10);
show "log₁₀(100) = " + log100; # Output: 2
# Exponential function
num eToThe2 = mathlib::exp(2);
show "e² = " + eToThe2; # Approximately 7.389
```
### Min and Max Functions
```razen
# Import the math library
lib mathlib;
# Find maximum
num maximum = mathlib::max(3, 7);
show "max(3, 7) = " + maximum; # Output: 7
# Find minimum
num minimum = mathlib::min(3, 7);
show "min(3, 7) = " + minimum; # Output: 3
# Works with multiple arguments
num maxOfMany = mathlib::max(5, 2, 9, 1, 7);
show "max(5, 2, 9, 1, 7) = " + maxOfMany; # Output: 9
```
### Modulo Operation
```razen
# Import the math library
lib mathlib;
# Calculate remainder
num remainder = mathlib::modulo(17, 5);
show "17 % 5 = " + remainder; # Output: 2
# Useful for cyclic operations
num hourIn24Format = 25;
num hourIn12Format = mathlib::modulo(hourIn24Format, 12);
show "25 o'clock in 12-hour format is " + hourIn12Format; # Output: 1
```
## Advanced Examples
### Distance Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate distance between two points
fun distance(num x1, num y1, num x2, num y2) {
# Calculate differences
num dx = mathlib::subtract(x2, x1);
num dy = mathlib::subtract(y2, y1);
# Square the differences
num dxSquared = mathlib::power(dx, 2);
num dySquared = mathlib::power(dy, 2);
# Sum and take square root
return mathlib::sqrt(mathlib::add(dxSquared, dySquared));
}
# Calculate distance between points (1,2) and (4,6)
num dist = distance(1, 2, 4, 6);
show "Distance between (1,2) and (4,6) is " + dist; # Output: 5
```
### Quadratic Equation Solver
```razen
# Import the math library
lib mathlib;
# Function to solve quadratic equations of the form ax² + bx + c = 0
fun solveQuadratic(num a, num b, num c) {
# Calculate discriminant
num discriminant = mathlib::subtract(
mathlib::power(b, 2),
mathlib::multiply(4, mathlib::multiply(a, c))
);
# Check if solutions are real
if (discriminant < 0) {
return "No real solutions";
}
# Calculate solutions
num sqrtDiscriminant = mathlib::sqrt(discriminant);
num denominator = mathlib::multiply(2, a);
num x1 = mathlib::divide(
mathlib::add(mathlib::multiply(b, -1), sqrtDiscriminant),
denominator
);
num x2 = mathlib::divide(
mathlib::subtract(mathlib::multiply(b, -1), sqrtDiscriminant),
denominator
);
# Return solutions
if (discriminant == 0) {
return "One solution: x = " + x1;
} else {
return "Two solutions: x₁ = " + x1 + ", x₂ = " + x2;
}
}
# Solve x² - 5x + 6 = 0
show solveQuadratic(1, -5, 6); # Output: "Two solutions: x₁ = 3, x₂ = 2"
# Solve x² - 4x + 4 = 0
show solveQuadratic(1, -4, 4); # Output: "One solution: x = 2"
# Solve x² + x + 1 = 0
show solveQuadratic(1, 1, 1); # Output: "No real solutions"
```
### Simple Interest Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate simple interest
fun calculateSimpleInterest(num principal, num rate, num time) {
# Convert rate to decimal (if given as percentage)
num rateDecimal = mathlib::divide(rate, 100);
# Calculate interest using formula: I = P * R * T
num interest = mathlib::multiply(
principal,
mathlib::multiply(rateDecimal, time)
);
# Calculate total amount
num totalAmount = mathlib::add(principal, interest);
# Return results as a map
map result = {
"principal": principal,
"rate": rate,
"time": time,
"interest": interest,
"totalAmount": totalAmount
};
return result;
}
# Calculate interest for a loan of $1000 at 5% for 2 years
map loanDetails = calculateSimpleInterest(1000, 5, 2);
# Display results
show "Loan Principal: $" + loanDetails["principal"];
show "Interest Rate: " + loanDetails["rate"] + "%";
show "Time Period: " + loanDetails["time"] + " years";
show "Interest Earned: $" + loanDetails["interest"];
show "Total Amount: $" + loanDetails["totalAmount"];
```
## Practical Application: Simple Statistics Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate basic statistics for a set of numbers
fun calculateStats(num values) {
# Check if array is empty
if (values.length == 0) {
return "Error: Empty array";
}
# Calculate sum
num sum = 0;
for (num i = 0; i < values.length; i = i + 1) {
sum = mathlib::add(sum, values[i]);
}
# Calculate mean
num count = values.length;
num mean = mathlib::divide(sum, count);
# Calculate variance and standard deviation
num sumSquaredDiff = 0;
for (num i = 0; i < count; i = i + 1) {
num diff = mathlib::subtract(values[i], mean);
sumSquaredDiff = mathlib::add(sumSquaredDiff, mathlib::power(diff, 2));
}
num variance = mathlib::divide(sumSquaredDiff, count);
num stdDev = mathlib::sqrt(variance);
# Find min and max
num min = values[0];
num max = values[0];
for (num i = 1; i < count; i = i + 1) {
min = mathlib::min(min, values[i]);
max = mathlib::max(max, values[i]);
}
# Calculate range
num range = mathlib::subtract(max, min);
# Return statistics as a map
map stats = {
"count": count,
"sum": sum,
"mean": mean,
"min": min,
"max": max,
"range": range,
"variance": variance,
"standardDeviation": stdDev
};
return stats;
}
# Sample data: test scores
num scores = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91];
# Calculate statistics
map statistics = calculateStats(scores);
# Display results
show "=== Statistics for Test Scores ===";
show "Count: " + statistics["count"];
show "Sum: " + statistics["sum"];
show "Mean: " + statistics["mean"];
show "Minimum: " + statistics["min"];
show "Maximum: " + statistics["max"];
show "Range: " + statistics["range"];
show "Variance: " + statistics["variance"];
show "Standard Deviation: " + statistics["standardDeviation"];
```
## Summary
The Math Library in Razen provides essential mathematical functions:
- Basic arithmetic operations (`add`, `subtract`, `multiply`, `divide`)
- Advanced math operations (`power`, `sqrt`, `abs`)
- Rounding functions (`round`, `floor`, `ceil`)
- Trigonometric functions (`sin`, `cos`, `tan`)
- Logarithmic and exponential functions (`log`, `exp`)
- Utility functions (`min`, `max`, `modulo`)
- Mathematical constants (`PI`, `E`)
These functions help you perform mathematical calculations efficiently in your Razen programs.
# Math Library (mathlib)
# Difficulty: 1
# Description: Examples of using the Math Library in Razen
## Introduction
The Math Library (`mathlib`) provides mathematical functions and constants for numerical operations in Razen. This library includes basic arithmetic, trigonometry, logarithms, and other common mathematical operations.
## Library Overview
### Math Library Functions
- `add` → Adds two numbers
- `subtract` → Subtracts the second number from the first (Note: corrected from "subtrack" in the documentation)
- `multiply` → Multiplies two numbers
- `divide` → Divides the first number by the second
- `power` → Raises a number to a specified power
- `sqrt` → Calculates the square root of a number
- `abs` → Returns the absolute value of a number
- `round` → Rounds a number to the nearest integer
- `floor` → Rounds a number down to the nearest integer
- `ceil` → Rounds a number up to the nearest integer
- `sin`, `cos`, `tan` → Trigonometric functions (angles in radians)
- `log` → Calculates the logarithm of a number with a specified base
- `exp` → Calculates e raised to the power of a number
- `random` → Generates a random number between 0 and 1
- `max` → Returns the largest of the provided numbers
- `min` → Returns the smallest of the provided numbers
- `modulo` → Returns the remainder of a division
### Math Constants
- `PI` → The mathematical constant π (3.141592...)
- `E` → The mathematical constant e (2.718281...)
## How to Use the Math Library
### Library Import
To use the Math Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib mathlib;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
mathlib::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
mathlib[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Basic Arithmetic Operations
```razen
# Import the math library
lib mathlib;
# Addition
num sum = mathlib::add(5, 3);
show "5 + 3 = " + sum; # Output: 8
# Subtraction
num difference = mathlib::subtract(10, 4);
show "10 - 4 = " + difference; # Output: 6
# Multiplication
num product = mathlib::multiply(6, 7);
show "6 * 7 = " + product; # Output: 42
# Division
num quotient = mathlib::divide(15, 3);
show "15 / 3 = " + quotient; # Output: 5
# Division with decimal result
num decimalResult = mathlib::divide(10, 4);
show "10 / 4 = " + decimalResult; # Output: 2.5
```
### Power and Roots
```razen
# Import the math library
lib mathlib;
# Power
num power = mathlib::power(2, 8);
show "2^8 = " + power; # Output: 256
# Square root
num sqrt = mathlib::sqrt(25);
show "√25 = " + sqrt; # Output: 5
# Using power for roots (cube root of 27)
num cubeRoot = mathlib::power(27, mathlib::divide(1, 3));
show "Cube root of 27 = " + cubeRoot; # Approximately 3
```
### Rounding Numbers
```razen
# Import the math library
lib mathlib;
# Round to nearest integer
num rounded = mathlib::round(3.7);
show "round(3.7) = " + rounded; # Output: 4
# Floor (round down)
num floored = mathlib::floor(3.7);
show "floor(3.7) = " + floored; # Output: 3
# Ceiling (round up)
num ceiling = mathlib::ceil(3.2);
show "ceil(3.2) = " + ceiling; # Output: 4
```
### Absolute Value
```razen
# Import the math library
lib mathlib;
# Absolute value
num absolute = mathlib::abs(-42);
show "abs(-42) = " + absolute; # Output: 42
# Absolute value of a positive number
show "abs(42) = " + mathlib::abs(42); # Output: 42
```
### Trigonometric Functions
```razen
# Import the math library
lib mathlib;
# Convert degrees to radians
fun toRadians(num degrees) {
return mathlib::multiply(degrees, mathlib::divide(mathlib::PI, 180));
}
# Calculate sine of 30 degrees
num sin30 = mathlib::sin(toRadians(30));
show "sin(30°) = " + sin30; # Output: 0.5
# Calculate cosine of 60 degrees
num cos60 = mathlib::cos(toRadians(60));
show "cos(60°) = " + cos60; # Output: 0.5
# Calculate tangent of 45 degrees
num tan45 = mathlib::tan(toRadians(45));
show "tan(45°) = " + tan45; # Approximately 1
```
### Logarithms and Exponentials
```razen
# Import the math library
lib mathlib;
# Natural logarithm (base e)
num ln = mathlib::log(mathlib::E, mathlib::E);
show "ln(e) = " + ln; # Output: 1
# Logarithm base 10
num log100 = mathlib::log(100, 10);
show "log₁₀(100) = " + log100; # Output: 2
# Exponential function
num eToThe2 = mathlib::exp(2);
show "e² = " + eToThe2; # Approximately 7.389
```
### Min and Max Functions
```razen
# Import the math library
lib mathlib;
# Find maximum
num maximum = mathlib::max(3, 7);
show "max(3, 7) = " + maximum; # Output: 7
# Find minimum
num minimum = mathlib::min(3, 7);
show "min(3, 7) = " + minimum; # Output: 3
# Works with multiple arguments
num maxOfMany = mathlib::max(5, 2, 9, 1, 7);
show "max(5, 2, 9, 1, 7) = " + maxOfMany; # Output: 9
```
### Modulo Operation
```razen
# Import the math library
lib mathlib;
# Calculate remainder
num remainder = mathlib::modulo(17, 5);
show "17 % 5 = " + remainder; # Output: 2
# Useful for cyclic operations
num hourIn24Format = 25;
num hourIn12Format = mathlib::modulo(hourIn24Format, 12);
show "25 o'clock in 12-hour format is " + hourIn12Format; # Output: 1
```
## Advanced Examples
### Distance Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate distance between two points
fun distance(num x1, num y1, num x2, num y2) {
# Calculate differences
num dx = mathlib::subtract(x2, x1);
num dy = mathlib::subtract(y2, y1);
# Square the differences
num dxSquared = mathlib::power(dx, 2);
num dySquared = mathlib::power(dy, 2);
# Sum and take square root
return mathlib::sqrt(mathlib::add(dxSquared, dySquared));
}
# Calculate distance between points (1,2) and (4,6)
num dist = distance(1, 2, 4, 6);
show "Distance between (1,2) and (4,6) is " + dist; # Output: 5
```
### Quadratic Equation Solver
```razen
# Import the math library
lib mathlib;
# Function to solve quadratic equations of the form ax² + bx + c = 0
fun solveQuadratic(num a, num b, num c) {
# Calculate discriminant
num discriminant = mathlib::subtract(
mathlib::power(b, 2),
mathlib::multiply(4, mathlib::multiply(a, c))
);
# Check if solutions are real
if (discriminant < 0) {
return "No real solutions";
}
# Calculate solutions
num sqrtDiscriminant = mathlib::sqrt(discriminant);
num denominator = mathlib::multiply(2, a);
num x1 = mathlib::divide(
mathlib::add(mathlib::multiply(b, -1), sqrtDiscriminant),
denominator
);
num x2 = mathlib::divide(
mathlib::subtract(mathlib::multiply(b, -1), sqrtDiscriminant),
denominator
);
# Return solutions
if (discriminant == 0) {
return "One solution: x = " + x1;
} else {
return "Two solutions: x₁ = " + x1 + ", x₂ = " + x2;
}
}
# Solve x² - 5x + 6 = 0
show solveQuadratic(1, -5, 6); # Output: "Two solutions: x₁ = 3, x₂ = 2"
# Solve x² - 4x + 4 = 0
show solveQuadratic(1, -4, 4); # Output: "One solution: x = 2"
# Solve x² + x + 1 = 0
show solveQuadratic(1, 1, 1); # Output: "No real solutions"
```
### Simple Interest Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate simple interest
fun calculateSimpleInterest(num principal, num rate, num time) {
# Convert rate to decimal (if given as percentage)
num rateDecimal = mathlib::divide(rate, 100);
# Calculate interest using formula: I = P * R * T
num interest = mathlib::multiply(
principal,
mathlib::multiply(rateDecimal, time)
);
# Calculate total amount
num totalAmount = mathlib::add(principal, interest);
# Return results as a map
map result = {
"principal": principal,
"rate": rate,
"time": time,
"interest": interest,
"totalAmount": totalAmount
};
return result;
}
# Calculate interest for a loan of $1000 at 5% for 2 years
map loanDetails = calculateSimpleInterest(1000, 5, 2);
# Display results
show "Loan Principal: $" + loanDetails["principal"];
show "Interest Rate: " + loanDetails["rate"] + "%";
show "Time Period: " + loanDetails["time"] + " years";
show "Interest Earned: $" + loanDetails["interest"];
show "Total Amount: $" + loanDetails["totalAmount"];
```
## Practical Application: Simple Statistics Calculator
```razen
# Import the math library
lib mathlib;
# Function to calculate basic statistics for a set of numbers
fun calculateStats(num values) {
# Check if array is empty
if (values.length == 0) {
return "Error: Empty array";
}
# Calculate sum
num sum = 0;
for (num i = 0; i < values.length; i = i + 1) {
sum = mathlib::add(sum, values[i]);
}
# Calculate mean
num count = values.length;
num mean = mathlib::divide(sum, count);
# Calculate variance and standard deviation
num sumSquaredDiff = 0;
for (num i = 0; i < count; i = i + 1) {
num diff = mathlib::subtract(values[i], mean);
sumSquaredDiff = mathlib::add(sumSquaredDiff, mathlib::power(diff, 2));
}
num variance = mathlib::divide(sumSquaredDiff, count);
num stdDev = mathlib::sqrt(variance);
# Find min and max
num min = values[0];
num max = values[0];
for (num i = 1; i < count; i = i + 1) {
min = mathlib::min(min, values[i]);
max = mathlib::max(max, values[i]);
}
# Calculate range
num range = mathlib::subtract(max, min);
# Return statistics as a map
map stats = {
"count": count,
"sum": sum,
"mean": mean,
"min": min,
"max": max,
"range": range,
"variance": variance,
"standardDeviation": stdDev
};
return stats;
}
# Sample data: test scores
num scores = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91];
# Calculate statistics
map statistics = calculateStats(scores);
# Display results
show "=== Statistics for Test Scores ===";
show "Count: " + statistics["count"];
show "Sum: " + statistics["sum"];
show "Mean: " + statistics["mean"];
show "Minimum: " + statistics["min"];
show "Maximum: " + statistics["max"];
show "Range: " + statistics["range"];
show "Variance: " + statistics["variance"];
show "Standard Deviation: " + statistics["standardDeviation"];
```
## Summary
The Math Library in Razen provides essential mathematical functions:
- Basic arithmetic operations (`add`, `subtract`, `multiply`, `divide`)
- Advanced math operations (`power`, `sqrt`, `abs`)
- Rounding functions (`round`, `floor`, `ceil`)
- Trigonometric functions (`sin`, `cos`, `tan`)
- Logarithmic and exponential functions (`log`, `exp`)
- Utility functions (`min`, `max`, `modulo`)
- Mathematical constants (`PI`, `E`)
These functions help you perform mathematical calculations efficiently in your Razen programs.