[ Java ] ラジアンと角度を相互に変換する ( Math.toDegrees )

Pocket

Java ではラジアンから角度に変換する関数 ( Math.toDegrees ) と角度からラジアンに変換する関数 ( Math.toRadians ) が用意されています。ここでは、参考として自前で相互に変換する関数を作成して結果を比較しています。

スポンサーリンク

なお、ラジアンの定義を知りたい場合は、『1rad.(ラジアン)の定義はどうなっているの?』を参照ください。

ラジアンと角度の相互変換プログラム
import java.math.*;

public class TestClass
{
    public static void main(String[] args) 
    {
        double ret; // 計算結果格納バッファ

        /*
         * 角度をラジアンに変換する
         */
        double rad = Math.PI * 2.0;
        
        // Javaで用意されている関数を使う
        ret = Math.toDegrees(rad);
        System.out.println("deg = " + ret); // deg = 360.0

        // 自前で作成した関数を使う
        ret = _toDegrees(rad);
        System.out.println("deg = " + ret); // deg = 360.0

        /*
         * 角度をラジアンに変換する
         */
        double deg = 180;

        // Javaで用意されている関数を使う
        ret = Math.toRadians(deg);
        System.out.println("rad = " + ret); // rad = 3.141592653589793

        // 自前で作成した関数を使う
        ret = _toRadians(deg);
        System.out.println("rad = " + ret); // rad = 3.141592653589793
    }

    /*
     * 角度をラジアンに変換する
     */
    private static double _toRadians(double deg)
    {
        return deg * Math.PI / 180.0;
    }

    /*
     * ラジアンを角度に変換する
     */
    private static double _toDegrees(double rad)
    {
        return rad * 180.0 / Math.PI;    
    }
}
スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *