Wednesday, 25 February 2015

Geometric Series in Java


Hi all.
I've just been using a website called www.compilejava.net to noodle around with some new Java that I've been learning during free periods at school. I was also revising geometric series for maths and decided to put the two together!

I came up with a programme which creates a class for handling geometric series and initialises a value for the first number in the series and the common ratio. Using knowledge from maths I was able to create a method within the class which assigns a value to each number in the series. The series being an array of integers.

Here is the code:

import java.lang.Math;

public class UI
{
  public static void main(String[] args)
  {
    GeometricSeries A = new GeometricSeries(1.0, 3.0);
    A.setGeometricSeries();
    A.printGeometricSeries();
   
  }
}

public class GeometricSeries
{
  private double[] intergerArray = new double[1000];
  private double firstTerm;
  private double commonRatio;
 
  public GeometricSeries(double a, double r)
  {
    this.firstTerm = a;
    this.commonRatio = r;
    intergerArray[0] = a;
  }
  public void setGeometricSeries()
  {
   for(int i = 1; i < 1000; i++)
   {
     if (intergerArray[i] == this.firstTerm)
     {}
     else
     {
     this.intergerArray[i] = (java.lang.Math.pow(((this.firstTerm * this.commonRatio)), (i - 1)));
     }
   }
   
  }
    public void printGeometricSeries()
    {
     for (int i = 1; i < 1000; i++)
        {
          System.out.println(this.intergerArray[i]);
        }
    }
   
  }

Just a quick programme to enforce my learning in both subjects. Nothing too fancy.
Thanks and until next time.

No comments:

Post a Comment