java - 我认为我的程序给出的黎曼和结果不准确
问题描述
这是我第一次发帖!
因此,作为我的微积分课程的额外学分项目,教授为我们提供了编写一个简单程序来计算用户指定曲线下面积的机会。我意识到这不是实现这一点的最佳方式,但他说这很好,但我认为这给了我错误的答案。有人可以帮忙吗?
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;
与代码无关:由于您有一个简单的多项式,因此您可以分析计算反导数并简单地评估该函数。
推荐阅读
- node.js - 节点,生成多个依赖的 shell 命令
- javascript - 两行中的 headerText - JS - Oracle Jet
- keyword - 在 gensim + 关键字提取中使用 pos_tagger 选项的正确方法
- r - 在 R markdown 中使用 unicode
- html - 使用 Bootstrap 是否意味着混合内容和布局?
- javascript - 当一些卡片有图像而一些卡片没有图像时,从 AJAX 调用生成 HTML(引导卡片)到 JSON 文件
- c# - C# MS Access INNER 加入语法错误
- html - 为图像加载 CSHTML 附加字符串
- wordpress - wordpress 多站点索引徽标图像 url 重定向
- php - 你知道为什么自动完成搜索不能正常工作吗?