• 0

[JAVA] Math problem


Question

I am trying to write a java program to do the trapezoid rule of the function y = 2.5e^(-x)sin(5x^2.1) + 1.4 for the interval of x = 1 to x = 5. Here is my code:

import java.util.Scanner;

public class Trapezoid
{
	public static void main(String[] args)
	{
		Scanner scan = new Scanner(System.in);

		int n; // number of chunks
		final int A = 1; // lower limit
		final int B = 5; // upper limit
		double area, width, x, areaA, areaB; // area and width of chunks and x = A + width

		System.out.print("Enter the number of chunk: ");
		n = scan.nextInt();

		width = (A + B) / n;

		areaA = (width /2) * ((2.5*Math.exp(-A)*Math.sin(5*Math.pow(A, 2.1)) + 1.4));
		areaB = (width /2) * ((2.5*Math.exp(-B)*Math.sin(5*Math.pow(B, 2.1)) + 1.4));
		area = 0;

		for(int i = 1; i < n; i++)
		{
			x = A + width * i;
			area = area + ((width / 2) * (2 * (2.5*Math.exp(-x)*Math.sin(5*Math.pow(x, 2.1)) + 1.4)));				
		}

		area = area + areaA + areaB;

		System.out.println("" + area);					
	}
}

I am trying it with different amounts of trapezoids of 5, 100, and 1000 and when I use 5 it gives me an answer and 100 and 1000 just give 0.0. I think I must be doing something wrong.

Here is the trapezoidal rule: http://en.wikipedia.org/wiki/Trapezoidal_rule

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

The problem is the mixing of integer and floating-point arithmetic. When you do:

width = (A + B) / n;

The result is 0 for n greater than A + B, because since A, B, and n are integers, the decimal part is cut off. It is then casted into the floating-point number "width" as 0.0.

The easy and most correct way around this problem is to use only floating-point variables.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.