リーマン積分器のコードは次のとおりです。
public class RiemannIntegrator {
public static void main (String [] args)
{
double lower = Double.parseDouble(args[args.length -2]);
double higher = Double.parseDouble(args[args.length -1]);
double[] coefficients = new double[args.length - 3];
if (args[0].equals("poly"))
{
for (int i = 1; i < args.length - 2; i++)
{
coefficients[i-1] = Double.parseDouble(args[i]);
}
System.out.println(integral("poly", coefficients, lower, higher));
}
}
private static double integral(String s, double[] function, double lowBound, double highBound)
{
double area = 0; // Area of the rectangle
double sumOfArea = 0; // Sum of the area of the rectangles
double width = highBound - lowBound;
if (s.equals("poly"))
{
for (int i = 1; i <= ((highBound - lowBound) / width); i++) // Represents # of rectangles
{
System.out.println("Rectangles:" + i);
for (int j = 0; j < function.length; j++) // Goes through all the coefficients
{
area = width * function[j] * Math.pow ( (double)( (i * width + lowBound + (i -1.0) * width + highBound) / 2.0 ),function.length- 1- j);
/*Above code computes area of each rectangle */
sumOfArea += area;
}
}
}
width = width / 2.0;
System.out.println("polynomial, function (of any length), lower boundary, higher boundary.");
function.toString();
System.out.println("Lower Bound:" + lowBound + ", Higher Bound: " + highBound + ".");
System.out.println("The integral is:");
return sumOfArea;
}
}
ほとんどの場合は機能しますが、計算が間違っていることが多く、どこで間違ったのかわかりません。たとえば、x^3+2x^2+3x の関数の和を求めたい場合、電卓と Wolfram Alpha で 2.416667 が得られます。しかし、私のプログラムでは、結果が 6 であることがわかります。これは、長方形の数に関係があるのではないかと思います。誰でも助けることができますか?