Using 'sqrt' and other std functions in Rust

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Volcano99
Posts: 56
Joined: Wed Dec 16, 2009 10:10 pm UTC
Location: 350 km SW of The Castle

Using 'sqrt' and other std functions in Rust

Postby Volcano99 » Wed May 28, 2014 11:25 am UTC

I am having some trouble using the 'sqrt' function in Rust.
First I attempted to just call sqrt, even though i didn't expect it to work.
Then I found out that there's a std::num::sqrt function at http://static.rust-lang.org/doc/0.10/st ... .sqrt.html, so I attempted to import it

Code: Select all

use std::num::sqrt;
fn my_square_root(n:int) -> int {
        std::num::sqrt(n)
}

This complains saying that unresolved import: there is no `sqrt` in `std::num`.
So i thought that I might not be importing it right ('import math.sqrt' vs 'from math import sqrt' in Python).

Next attempt was importing std::num and calling std::num::sqrt. This makes the 'use std::num;' line correct, but breaks at the call with the error unresolved name `std::num::sqrt`.

Then i found this StackOverflow post: http://stackoverflow.com/questions/1793 ... -in-stdnum whose error looks suspiciously like mine. So i went and tried:

Code: Select all

use std::float;
fn my_square_root(n:int) -> float {
        (n as float).sqrt()
}

but apparently there is no `float` in `std`. I can't use float in my code either. Was the float type removed?

I noticed there are a lot of incompatible versions. I'm using 0.11.0 nightly downloaded from http://www.rust-lang.org/

Any help will be appreciated!

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Using 'sqrt' and other std functions in Rust

Postby Nyktos » Wed May 28, 2014 2:11 pm UTC

Yeah, this is the problem with Rust right now: everything keeps drastically changing. The float type has indeed been removed; you'll probably want f64 instead.

Volcano99
Posts: 56
Joined: Wed Dec 16, 2009 10:10 pm UTC
Location: 350 km SW of The Castle

Re: Using 'sqrt' and other std functions in Rust

Postby Volcano99 » Wed May 28, 2014 9:27 pm UTC

I casted to f64 and it worked! Thank you!

Btw, I'm doing some of the project euler puzzles to get the hang of it. This was problem number 3.
This is the final code: it just prints the prime factors of the number.

Code: Select all

fn get_next_factor(n: int) -> int {
    for i in range(2, ((n as f64).sqrt() +1.0) as int) {
        if n % i == 0 {
            return i;
        }
    }
    return n;
}

fn main() {
    let mut number = 600851475143;
    while number != 1 {
        let factor = get_next_factor(number);
        number /= factor;
        println!("{}", factor);
    }
}

I'm quite unhappy with how that long line turned out, but I guess that's the price you have to pay when using strong, static typing!

I'm having some trouble figuring out how to iterate over characters in a string (to check if said string is a palindrome or not) but I'm sure I'll figure it out. Casting to ~[u8] is quite tempting.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Using 'sqrt' and other std functions in Rust

Postby Nyktos » Thu May 29, 2014 12:08 am UTC

Strings have a chars() method. Definitely don't transmute to ~[u8] since that'll be straight-up wrong if your string isn't ASCII.

Derek
Posts: 2181
Joined: Wed Aug 18, 2010 4:15 am UTC

Re: Using 'sqrt' and other std functions in Rust

Postby Derek » Thu May 29, 2014 12:59 am UTC

Does Rust not have an integer squareroot function? If not, you could create your own to hide the nastiness of converting types from the rest of your code.

Volcano99
Posts: 56
Joined: Wed Dec 16, 2009 10:10 pm UTC
Location: 350 km SW of The Castle

Re: Using 'sqrt' and other std functions in Rust

Postby Volcano99 » Thu May 29, 2014 7:53 am UTC

Documentation for 0.8 and 0.9 says that mathematic functions are implemented for the primitive numeric types in std::{u8, u16,u32, u64, uint, i8, i16, i32, i64, int, f32, f64}.
sqrt in particular was in the trait Algebraic, which was implemented for f32, f64 and float, contradicting the previous line :roll:.

Now it is implemented in the trait Float, which is implemented for f32 and f64. float was removed. This trait is both in std::num and core::num, but i guess i'm using the later version (core is always imported right?).

Traits are confusing. Continually changing the spec is even more confusing, and I haven't started thinking about lifetimes yet...

http://web.mit.edu/rust-lang_v0.8/doc/s ... braic.html
http://static.rust-lang.org/doc/master/ ... Float.html

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Using 'sqrt' and other std functions in Rust

Postby PM 2Ring » Fri May 30, 2014 8:20 am UTC

Derek wrote:Does Rust not have an integer squareroot function? If not, you could create your own to hide the nastiness of converting types from the rest of your code.

If you do that, surely you'd write a purely integer-based one so you don't have the added expense of converting between int and float.

Volcano99
Posts: 56
Joined: Wed Dec 16, 2009 10:10 pm UTC
Location: 350 km SW of The Castle

Re: Using 'sqrt' and other std functions in Rust

Postby Volcano99 » Fri May 30, 2014 9:56 am UTC

Disclaimer: I don't actually know x86_64 assembly.

I don't think it is expensive, the call looks like this (some lines removed):

Code: Select all

cvtsi2sdq 0x68(%rsp),%xmm0
callq  404710 <_ZN3f649f64.Float4sqrt20ha18fdeaca09e5435Dda4v0.0E>
cvttsd2si 0x48(%rsp),%rax

cvtsi2sdq and cvttsd2si cast to double and to int respectively.
f64::Float::sqrt then calls "sqrtsd %xmm0,%xmm0": I guess casting and using a hardware instruction beats computing the square root manually.

If optimized, the code just calls these 3 instructions in order, inlining the Float::sqrt call, which is kinda awesome.

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Using 'sqrt' and other std functions in Rust

Postby PM 2Ring » Fri May 30, 2014 11:37 am UTC

Ah, ok. I guess that is going to be cheaper than rolling your own int sqrt.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 6 guests