Advanced
Java
Services
|
JAVA-Praktikum |
|
Eine Klasse mit mathematischen Methoden (Lösung) |
// ------------------------------ MathUtil.java ------------------------------- \\
public class MathUtil
{
// ------------------------------- round() --------------------------------- \\
public static double round(double x, int stellen)
{
double tmp = Math.pow(10,stellen) ;
return Math.rint( tmp*x ) / tmp ;
//return Math.rint( Math.pow(10,stellen)*x ) / Math.pow(10,stellen) ;
}
// -------------------------------- max() ---------------------------------- \\
public static int max(int arr[])
{
int max = arr[0] ;
for(int i=1; i<arr.length; i++)
if (max<arr[i]) max = arr[i] ;
return max;
}
// -------------------------------- max() ---------------------------------- \\
public static double max(double arr[])
{
double max = arr[0] ;
for(int i=1; i<arr.length; i++)
if (max<arr[i]) max = arr[i] ;
return max;
}
// -------------------------------- sgn() ---------------------------------- \\
public static int sgn(double x)
{
return x>0 ? 1 : x<0 ? -1 : 0 ;
}
// -------------------------------- kgV() ---------------------------------- \\
public static double kgV(int a, int b)
{
if (a*b==0) return 0 ;
double max = a < b ? b : a ;
double min = a < b ? a : b ;
int i;
for(i=1 ; (i*max)%min != 0 ; i++)
;
return i*max ;
}
// -------------------------------- ggT() ---------------------------------- \\
public static double ggT(int a, int b)
{
if (a*b==0) return 0 ;
return a*b/ kgV(a,b) ;
}
// ------------------------------- fibo() ---------------------------------- \\
public static double fibo(int n)
{
if (n < 0 || n > 92 )
return -1 ;
if (n<=1) return n;
long fibo=0, vor=0, vorvor=1 ;
vor = 0 ; vorvor = 1 ;
for(int i=0; i<n ; i++ )
{
fibo = vor + vorvor ;
vorvor = vor ;
vor = fibo;
}
return fibo ;
}
// -------------------------------- fak() ---------------------------------- \\
public static double fak(int n)
{
if (n<0) return Double.NaN ;
if (n<=1) return 1;
if (n>92) return Double.NaN ;
double fak=1 ;
for(int i=1; i<n; i++)
fak = fak*(i+1) ;
return fak;
}
// ------------------------------ isPrime() -------------------------------- \\
public static boolean isPrime(long p)
{
if (p==0) return false;
if (p<0) p = -p ;
if (p==1) return false;
if (p==2) return true;
if (p%2==0) return false;
for (int i=3 ; i<=Math.sqrt(p) ; i+=2)
if (p%i==0)
return false;
return true;
}
// ------------------------------- binko() --------------------------------- \\
public static double binko(int n, int v)
{
return 0 ;
}
} // end class MathUtil