我遇到了最小值未正确设置的问题。最大值设置完美,但我知道最小值应该小于0.运行此片段,似乎最小值永远不会被设置。有任何想法吗?确定函数的极值
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 <0所定义; Math.sqrt(8 * x)是虚数。无论在Wolfram Alpha上的函数都不是您在Java代码中实际使用的函数。 –
那么我该如何解决这个问题呢?只需用'Math.sqrt(8 * x)替换为0? – kneeki
你可以通过在Java中编写正确的函数来解决这个问题,因为你在这里看到的并不像你提供的图表。 –