Where is the sine function?

2019-04-21 14:36发布

问题:

Simple question: Where is sin()? I've searched and only found in the Rust docs that there are traits like std::num::Float that require sin, but no implementation.

回答1:

The Float trait was removed, and the methods are inherent implementations on the types now. That means there's a bit less typing to access math functions:

fn main() {
    let val: f32 = 3.14159;
    println!("{}", val.sin());
}

However, it's ambiguous if 3.14159.sin() refers to a 32- or 64-bit number, so you need to specify it explicitly. Above, I set the type of the variable, but you can also use a type suffix:

fn main() {
    println!("{}", 3.14159f64.sin());
}

You can also use fully qualified syntax:

fn main() {
    println!("{}", f32::sin(3.14159));
}


回答2:

Float is Trait, include implementation, import this to apply for f32 or f64.

use std::num::Float;

fn main() {
    println!("{}", 1.0f64.sin());
}


标签: math rust sin