👏

Rustで三角関数を扱いたい

2022/07/18に公開
2

きっかけ

ABC259のB問で、rustでの三角関数の扱い方がわからなかったのでメモとして残します。

三角関数

rustで\sin \theta, \cos\theta, \tan \thetaはそれぞれ以下のように書きます。

theta.sin();
theta.con();
theta.tan();

順番が逆ですね、なれるまでかなり苦労しそうです...。
https://doc.rust-lang.org/std/primitive.f64.html

追記(2022/10/10)

別の書き方をコメントにて教えていただきました。
DenTakuさん、ありがとうございます!

f64::sin(theta)
f64::cos(theta)
f64::tan(theta)

おまけ : 実際に解いてみた

円周率

回転角度を度数で与えられているので、まずはラジアンに変換します。
円周率\piは定数として用意されているのでそのまま使いましょう。

use std::f64::consts::PI;
let rad = d/180. * PI;

https://doc.rust-lang.org/std/f64/consts/constant.PI.html

2次元の回転行例

今回は回転行列を使って半ば公式に突っ込む形で導出します。

点(a,b)を原点中心に\theta回転させたときの点(x, y)は

\begin{pmatrix} x \\ y \\ \end{pmatrix} = \begin{pmatrix} \cos \theta & - \sin \theta \\ \sin \theta & \cos \theta \end{pmatrix} \begin{pmatrix} a \\ b \end{pmatrix}

です。
Rustでは以下のように書けます。

let x = a*rad.cos() - b*rad.sin();
let y = a*rad.sin() + b*rad.cos();

もしくは

let x = a*f64:cos(rad) - b*f64::sin(rad);
let y = a*f64::sin(rad) + b*f64::cos(rad);

あとは入力、出力を書けば無事ACゲットです。

拙作
use proconio::input;
 
use std::f64::consts::PI;
 
fn main() {
    input!{
        a: f64,
        b: f64,
        d: f64
    }
 
    let rad = d/180. * PI;
 
    let x = a*rad.cos() - b*rad.sin();
    let y = a*rad.sin() + b*rad.cos();

    println!("{} {}", x, y);
}

最後に

今までやったどの言語とも書き方が異なるのではじめは苦労しそうです。

Discussion