首页 > 解决方案 > 我认为我的程序给出的黎曼和结果不准确

问题描述

这是我第一次发帖!

因此,作为我的微积分课程的额外学分项目,教授为我们提供了编写一个简单程序来计算用户指定曲线下面积的机会。我意识到这不是实现这一点的最佳方式,但他说这很好,但我认为这给了我错误的答案。有人可以帮忙吗?

import java.util.*;

public class RiemannSum2 {
    public static void main(String args []) {
        System.out.println("This is a Riemann Sum Calculator. This calculator accepts polynomials in the form of a(x)^ex + b(x)^ex2 + c, where c is a constant.");

        System.out.print("Enter the first coeffecient of the polynomial: ");
        Scanner sc = new Scanner(System.in);
        int firstCoe = sc.nextInt();

        System.out.print("Enter the exponent of the first term: ");
        int firstExp = sc.nextInt();

        System.out.print("Enter the second coeffecient of the polynomial: ");
        int secondCoe = sc.nextInt();

        System.out.print("Enter the exponent of the second term: ");
        int secondExp = sc.nextInt();

        System.out.print("Enter the third term of the polynomial: ");
        int thirdTerm = sc.nextInt();

        System.out.print("Enter the x value that you want to start the Riemann Sum: ");
        int startX = sc.nextInt();

        System.out.print("Enter the x value to stop the Riemann Sum: ");
        int endX = sc.nextInt();


        String poly = (firstCoe+"x^"+firstExp+"+"+secondCoe+"x^"+secondExp+"+"+thirdTerm);

        System.out.println("Your polynomial is: "+poly);
        System.out.print("Enter the number of rectangles you want: ");
        int rectangles = sc.nextInt();

        double numerator = (endX-startX);
        double rectanglesD = (double)rectangles;

        double constantWidth = numerator/rectanglesD;

        System.out.println("This is the constant width: " + constantWidth);
        double totalSum = 0;
        //System.out.println(totalSum);
        for(int i = 0; i < rectangles ; i++) {

            totalSum = totalSum+((Math.pow((firstCoe * (i/constantWidth)), firstExp)) + (Math.pow((secondCoe * (i/constantWidth)), secondExp))+thirdTerm);

        }

        totalSum = totalSum*constantWidth;
        System.out.println("The Riemann Sum of your polynomial is roughly equivalent to: "+ totalSum);

    }
}

标签: java

解决方案


您用于(i/constantWidth)计算函数的参数 ( x)。但是,应该是

double x = startX + i * constantWidth;

此外,您的系数应该在pow函数之外。否则,它们也会被取幂。删除一些多余的括号使公式更容易阅读。像这样:

double x = startX + i * constantWidth;
totalSum = totalSum
               + firstCoe * Math.pow(x, firstExp)
               + secondCoe * Math.pow(x, secondExp)
               + thirdTerm;

与代码无关:由于您有一个简单的多项式,因此您可以分析计算反导数并简单地评估该函数。


推荐阅读