Math Class (Cont.)


The Math.abs(x) method returns the absolute (positive) value of x:

 System.out.println( Math.abs( 3.0-16.0 ) );      // Output: 13.0

The Math.random( ) returns a random number between 0 (inclusive), and 1 (exclusive):

 // Returns an integer between 0 and 99, inclusively.
 System.out.println( (int) ( Math.random( ) * 100 ) );

For a complete reference of Math methods, go to Java Math Methods Reference.

Fibonacci.java (calculating Fibonacci numbers)
 /**********************************************************
  *                                                        *
  *   Fibonacci numbers are starting from 0 and 1 such     *
  *   that each number is the sum of the two preceding     *
  *   ones.  For example, 0, 1, 1, 2, 3, 5, 8, 13, ...     *
  *                                                        *
  **********************************************************/

 public class Fibonacci {
   public static void main( String[ ] args ) {
     // Convert the input number from a string to an integer.
     int  number = Integer.parseInt( args[0] );
     // Define first two numbers of the series.
     int  a = 0;
     int  b = 1;
     // Variable to hold the sum
     int  sum = 0;

     System.out.println( "Fibonacci series = " );
     System.out.print  (   a + " " + b + " "   );

     for ( int i = 2; i < ; i++ ) {
       // Add the last two numbers.
       sum = a + b;
       // Shift the two numbers one place in the series.
       a   = b;
       b   = sum;
       System.out.print(  + " " );
     }
   }
 }
shell> java Fibonacci (≥ 2)            




      I entered 10 puns in a pun contest    
      hoping one would win,    
      but no pun in ten did.