Search code examples
rusttrigonometry

What is the idiomatic way to write the sine of the negative of an angle in Rust?


Let fi be an f64 angle value. The sine of -fi can be written in rust in the following two ways

let fi : f64 = PI/2;
let s1 = (-fi).sin();
let s2 = f64::sin(-fi);

It seems that form 1 is more common among rust programmers. Are there practical advantages of this form, apart from style?

Edited: Changed cosine to sine for the example to make sense. Changed the question to make it more technical/factual.


Solution

  • In general, form 1 is going to be more common in Rust. It may look bizarre to writers of many languages, but it seems very natural to me as a Rust and Ruby programmer. (To be fair, Ruby uses Math.cos(-Math::PI/2), but it does have many methods on Float.)

    As mentioned in the comments, it makes refactoring easier. If you decide to extend your code to be generic over floating-point types, such as with the num-traits crate, then it's going to be a lot nicer to work with than T::cos(-f1). As a person who hates having to change lots of things when refactoring, it seems logical to me.

    This is also consistent with how other parenthesized expressions work in Rust, such as (1..10).map(|x| x * 2). Nobody really wants to write the struct name there. As a code readability rule, if I'm in doubt, when in Rome, do as the Romans.

    However, the two syntaxes are completely functionally identical, and as such this is a style decision. As long as you're consistent and you and any collaborators are the same page, it ultimately doesn't matter.