这是我在这里的第一篇文章!
因此,作为我的微积分课程的额外学分项目,教授为我们提供了编写一个简单的程序的机会,该程序可以计算用户指定曲线下的面积。我意识到这不是实现这一点的最佳方式,但他说这很好,但我认为这给了我错误的答案。谁能帮忙?
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);
}
}
您可以使用(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;
与代码无关:由于您有一个简单的多项式,因此您可以通过分析方式计算反导数并简单地计算该函数。