Rust Lang

# Rust Math Library

Although Rust does not provide a standalone module for performing math operations, it provides a set of methods that allow us to perform mathematical operations.

Let us explore these methods and how we can use them to do math operations in Rust.

## Rust f64 Primitive Type

Most math functions and methods are defined in the Rust f64 primitive type. This is a 64-bit floating-point value.

An example of an f64 type in Rust is as shown:

let i = 3.141_f64;

Using the f64 type, we access useful math functions as illustrated in this guide.

## Square Root.

To get the square root of a number using Rust, we can use the sqrt function as shown in the example below:

fn main() {

let var = 121.0_f64;

println!("Square root of {} is {}: ", var, var.sqrt());

}

The above example should return the square root of 121.0. ## Min and Max

Rust provides min and max functions to determine the minimum and maximum value for a given pair, respectively.

An example code is as shown:

fn main() {

let x = 100.23_f64;

let y = 3.0_f64;

println!("min value: {}", x.min(y));

println!("max value: {}", x.max(y));

}

The example above returns the minimum and maximum of the two values. ## Absolute

We use the abs function to determine the absolute value for a given floating-point value. An example is as shown:

fn main() {

let j = -3.45_f64;

println!("{}", j.abs());

}

The code above should return the absolute value for the -3.45 as shown below: ## Trigonometric Functions

Rust supports trigonometric functions such as tan, sin, cos and their inverses. Example usage is as shown:

fn main() {

let dg = 32.0_f64;

let inv = 0.39_f64;

println!("Tan: {}: ", dg.tan());

println!("Inverse Tan: {}: ", inv.atan());

println!("Sin: {}: ", dg.sin());

println!("Inverse Sin: {}: ", inv.asin());

println!("Cosine: {}: ", dg.cos());

println!("Inverse Cosine: {}: ", inv.acos());

}

You can also determine hyperbolic values for both tan, sin and cos using tanh, sinh, and cosh functions.

The output from the above program is as shown: ## Cube Root

To determine the cube root of a value, use the cbrt function as shown in the example below:

let x = 8.0_f64;

println!("Cube root of 8: {}", x.cbrt())

The output is as shown: ## Logarithm

To determine the logarithm of a specific value to a certain base, you can use the log function. The syntax is as shown:

log(self, base)

An example is as shown:

let x = 8.0_f64;

println!("Log of {} to base 10: {}", x, x.log(10.0));

The output is as shown: ## Conclusion

This guide illustrates various mathematical functions and how to implement them in Rust. You can check the documentation shown below: 