【发布时间】:2016-04-11 22:26:18
【问题描述】:
我遇到了未正确设置最小值的问题。最大值设置得很好,但我知道最小值应该小于 0。运行这个 sn-p,似乎从来没有设置最小值。有什么想法吗?
public class FindingExtrema {
public static void main(String[] args) {
double lowestPoint = 0;
double highestPoint = 0;
double y;
double x = -1;
int timesCalculated = 0;
while (x <= 3) {
y = run(x);
if (y < lowestPoint) {
lowestPoint = y;
System.out.printf("y: %1$.5f", y);
}
if (y > highestPoint) {
highestPoint = y;
}
x += .00001;
timesCalculated++;
}
System.out.println("Done!");
System.out.printf("Lowest: %1$.5f, Highest: %2$.5f; Calculated %3$d times\n", lowestPoint, highestPoint, timesCalculated);
}
private static double run(double x) {
return Math.cbrt(2 * x) - Math.sqrt(8 * x) + x + 16;
}
}
【问题讨论】:
-
你的函数没有为 x
-
那我该如何解决呢?只需将 `Math.sqrt(8 * x) 替换为 0?
-
你可以通过在 Java 中编写正确的函数来解决这个问题,因为你在这里看到的和你提供的图表完全不一样。
-
这条曲线在我看来就像一个立方。该公式应涉及
Math.pow(..., 3)和Math.pow(..., 2),而不是sqrt和cbrt。 -
应该是
2 * x * x * x - 8 * x * x + x + 16。