Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use std::num::sqrt to compute the square root of a number?

Tags:

rust

I want to take the square root of a number.

I looked at the documentation here, and wrote use std::num; at the top of my program which I thought would have allowed me to sqrt. This doesn't work though, so what do I need to do to actually use std::num::sqrt?

let upperLimit: i64 = sqrt(num as f64) + 1; //doesnt work

I'm very new to Rust coming from c++, so I really don't understand that real use of use.

like image 333
Syntactic Fructose Avatar asked Aug 06 '14 16:08

Syntactic Fructose


People also ask

How do you find the square root of a number in C++?

The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file. Mathematically, sqrt(x) = √x .

How do you find the square root of a number code?

Method 1: Using inbuilt sqrt() function: The sqrt() function returns the sqrt of any number N.

How do you print the square root of a number in Python?

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math.sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.


2 Answers

Since Rust 1.0, the following should be used:

let upperLimit = (number as f64).sqrt() as i64 + 1;

Or, equivalently:

let upperLimit = f64::sqrt(number) as i64 + 1;

See the docs for f64::sqrt.

like image 131
Dave Vogt Avatar answered Jan 01 '23 22:01

Dave Vogt


Editor's Note: This historical answer predates Rust 1.0 and is no longer applicable.

With use std::num; you "import" the whole module and access members with num::*:

use std::num;

let upperLimit: i64 = num::sqrt(num as f64) + 1;

If you want to use sqrt directly you have to import it as use std::num::sqrt;:

use std::num::sqrt;

let upperLimit: i64 = sqrt(num as f64) + 1;
like image 28
Arjan Avatar answered Jan 01 '23 22:01

Arjan