简体   繁体   English

简单的数学到java练习

[英]Simple math to java practice

The assignment is to:任务是:

  • Create the java statement that will produce f(x) = 2x3 - 8x2 + x + 16.创建将产生 f(x) = 2x3 - 8x2 + x + 16 的 java 语句。
  • Write a Java program that will find the extrema (both high and low) for the function in part 1 across the closed interval (-1, 3).编写一个 Java 程序,该程序将在闭区间 (-1, 3) 内找到第 1 部分中函数的极值(高低)。

I don't know what I am doing wrong here exactly but I am getting an infinite number of 9.09.09 and so on.我不知道我在这里到底做错了什么,但我得到了 9.09.09 等等的无限数字。

import java.util.*;
import java.math.*;

public class Extrema
{
   public static void main(String[] args)
   {
      double step = 0.00001;
      double x = -1.0;
      double xn = 3;
      double highest = calc(x);
      while (x <= xn)
      {
         double f = calc(x);
         if (f > highest)
         {
            highest = f;
         }
         step++;
         System.out.print(highest);
      }
   }
   public static double calc(double x)
   {
      double f = 2*Math.pow(x, 1/3) - 8*Math.pow(x, 2) + x + 16;
      return f;
   }
}

Add x+=step at the end of (inside) the while loop.在 while 循环的末尾(内部)添加x+=step

import java.util.*;
import java.math.*;

public class Extrema
{
   public static void main(String[] args)
   {
      double step = 0.00001;
      double x = -1.0;
      double xn = 3;
      double highest = calc(x);
      while (x <= xn)
      {
         double f = calc(x);
         if (f > highest)
         {
            highest = f;
         }
         x += step;
      }
     System.out.println(highest);
   }
   public static double calc(double x)
   {
      double f = 2*Math.pow(x, 3) - 8*Math.pow(x, 2) + x + 16;
      return f;
   }
}

This outputs: 16.03175629885453 on my system.这在我的系统上输出: 16.03175629885453

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM