Example #1
0
 public Function add(Function f) {
   Quadratic q = (Quadratic) f;
   for (int x = 0; x < a.length; x++) {
     a[x] += q.get()[x];
   }
   return this;
 }
Example #2
0
  /** Executes the program. */
  public static void main(String[] args) {
    double a, b, c;
    double start;
    double end;
    int intervals;
    double leftRiemannSum, rightRiemannSum, exactIntegral;
    int[] space =
        new int[2]; // creates an array to store the indices of spaces that appear in the input.
    int j = 0;

    System.out.println(
        "Enter the three coefficients of a quadratic function separated with spaces:");
    Scanner keyboard = new Scanner(System.in);
    String input1 = keyboard.nextLine();

    /* loops through the input to locate spaces and stores their indices */
    for (int i = 0; i < input1.length(); i++) {
      if (input1.charAt(i) == ' ') {
        space[j] = i;
        j++;
      }
    }

    /* retrieves the values of coefficients and converts them to doubles */
    a = Double.parseDouble(input1.substring(0, space[0]));
    b = Double.parseDouble(input1.substring(space[0] + 1, space[1]));
    c = Double.parseDouble(input1.substring(space[1] + 1));

    do {
      System.out.println(
          "Enter the start point and end point of the integration separared with a space: ");
      String input2 = keyboard.nextLine();
      start = Double.parseDouble(input2.substring(0, input2.indexOf(' ')));
      end = Double.parseDouble(input2.substring(input2.indexOf(' ') + 1));
    } while (end
        < start); // asks the user to enter the intervals again if the start point is greater than
                  // the end point

    do {
      System.out.println("Enter the number of partitions of the integration: ");
      intervals = keyboard.nextInt();
    } while (intervals
        <= 0); // asks the user to enter the number of partitions again if it is less than or equal
               // to 0

    // Calculates the integral
    Quadratic integral = new Quadratic(a, b, c);
    leftRiemannSum = integral.leftRiemannSum(start, end, intervals);
    rightRiemannSum = integral.rightRiemannSum(start, end, intervals);
    exactIntegral = integral.integrate(start, end);

    // Prints the results
    System.out.println();
    System.out.println("Interval: [" + start + "," + end + "]");
    System.out.println("Partitions: " + intervals);
    System.out.println("Left Riemann Sum: " + leftRiemannSum);
    System.out.println("Right Riemann Sum: " + rightRiemannSum);
    System.out.println("Exact Integral: " + exactIntegral);

    System.exit(0);
  }