Java java.langパッケージのMathクラス

Mathクラス

Mathクラスは、幾何学、三角法、浮動小数点のような数学に関連するメソッドを提供する。
Mathクラスはfinalクラスであるため、継承できない。
Mathクラスのコンストラクタはprivateアクセス修飾子で宣言されているためインスタンスを生成できず、メンバー変数とメソッドはすべてstaticで宣言されている。

Mathの主な例

次のプログラムは、Mathクラスのメソッドを使用した例である。

package com.devkuma.basic.math;

public class Mathematics {

    public static void main(String[] args) {
        System.out.println("abs(10.6) :" + Math.abs(10.6));
        System.out.println("ceil(10.3) : " + Math.ceil(10.3));
        System.out.println("floor(10.3) : " + Math.floor(10.3));
        System.out.println("max(3, 5) : " + Math.max(3, 5));
        System.out.println("min(3, 5) : " + Math.min(3, 5));
        System.out.println("random() : " + Math.random());
        System.out.println("round(10.5) : " + Math.round(10.5));
        System.out.println("rint(10.3) : " + Math.rint(10.3));
    }
}

実行結果:

abs(10.6) :10.6
ceil(10.3) : 11.0
floor(10.3) : 10.0
max(3, 5) : 5
min(3, 5) : 3
random() : 0.3319476750319902
round(10.5) : 11
rint(10.3) : 10.0

Math.signum

Mathで数値の符号を取得する方法を紹介する。

package com.devkuma.basic.math;

public class MathSignum {
    public static void main(String[] args) {
        double plus = Math.signum(100); // 1.0
        double zero = Math.signum(0); // 0.0
        double minus = Math.signum(-100); // -1.0

        System.out.println(plus);
        System.out.println(zero);
        System.out.println(minus);
    }
}

実行結果:

1
0
-1
入力値 signum()戻り値
100(正数) 1
0(ゼロ) 0
-100(負数) -1

Mathクラス変数

変数 説明
E 自然対数定数(e: 2.718…)の値
PI 円周率(3.14…)の値

Mathの主なメソッド

メソッド 説明
static int abs(int a) aの絶対値をintで返す。
static long abs(long a) aの絶対値をlongで返す。
static float abs(float a) aの絶対値をfloatで返す。
static double abs(double a) aの絶対値をdoubleで返す。
static double ceil(double a) aの小数点以下を切り上げた値を返す。
static double floor(double a) aの小数点以下を切り捨てた値を返す。
static int max(int a, int b) a、bのうち大きい値をintで返す。
static long max(long a, long b) a、bのうち大きい値をlongで返す。
static float max(float a, float b) a、bのうち大きい値をfloatで返す。
static double max(double a, double b) a、bのうち大きい値をdoubleで返す。
static int min(int a, int b) a、bのうち小さい値をintで返す。
static long min(long a, long b) a、bのうち小さい値をlongで返す。
static float min(float a, float b) a、bのうち小さい値をfloatで返す。
static double min(double a, double b) a、bのうち小さい値をdoubleで返す。
static double random() 任意の値を返す。
static long round(double a) aの小数点以下を四捨五入した値を返す。
static double rint(double a) aに最も近い整数を返す。
static double sin(double a) aのサイン値を返す。
static double cos(double a) aのコサイン値を返す。
static double tan(double a) aのタンジェント値を返す。
static double sqrt(double a) aの平方根の値を返す。