Java Standard: Math

Aus Wikibooks


Die Klasse Math ist das Matheobjekt mit allen Operationen für einfache numerische Berechnungen. Neben Konstanten PI und E werden auch viele mathematische Operationen wie Wurzelziehen, Exponentialzahlen, Sinus und Cosinus zur Verfügung gestellt. Alle Konstanten und Methoden in der Math-Klasse sind static, damit man kein eigenes Math-Objekt für jede Berechnung anlegen muss. Der Ergebnistyp fast aller Operationen ist double.


Konstanten: PI, E

  double wert = Math.PI;

Wurzelziehen, Logarithmus und Exponentialfunktion: sqrt, log, pow

  double x = Math.sqrt( 2 );
  double y = Math.pow( 2,10 );  // 2^10 = 1024

Trigonometrische Funktionen: sin, cos, acos, asin, atan, atan2

  double wert  = Math.sin( 0.0 );
  double wert2 = Math.sin( Math.PI );

Wertetabelle für die ersten 10 Sinuswerte im Intervall [0..2*PI]

  double schrittweite = 2.0*Math.PI/10.0;
  for( double x=0.0; x<=2*Math.PI; x=x+schrittweite )
  {
    System.out.println( "f( "+x+" ) = "+Math.sin( x ));
  }

Minimum und Maximum: min, max

   int x = Math.min( 2,4 );  //Ergebnis ist 2 
   int y = Math.max( 2,4 );  //Ergebnis ist 4

Absolutwert, Runden und Abschneiden: abs, ceil, floor, rint, round

  double x = Math.abs( -4.1 );   //Ergebnis ist 4.1
  int    y = Math.round( 4.2 );  //Ergebnis ist 4

Umrechnung Grad (0..360) in Radian (0..2*PI)

  x = Math.toDegrees( Math.PI );
  y = Math.toRadians( 90 );

Pseudozufallswert ausgeben aus dem Bereich von größer oder gleich 0.0 bis kleiner 1.0

  double x = Math.random();