-4

The assignment is to:

  • Create the java statement that will produce f(x) = 2x3 - 8x2 + x + 16.
  • 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).

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.

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;
   }
}
CMPS
  • 7,733
  • 4
  • 28
  • 53

1 Answers1

0

Add x+=step at the end of (inside) the while loop.

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.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • After the first round, that will skip some values of `x`, since `step` is also increasing. – Numeron Apr 08 '14 at 04:12
  • @Numeron, I am aware of that, but I was not sure what the intent was. – merlin2011 Apr 08 '14 at 04:13
  • @Numeron, I have edited it to match his top-level description of what he's trying to do. – merlin2011 Apr 08 '14 at 04:16
  • @merlin2011 Thank you so much! To do the lowest, I'd do it while x >= xn, right? – user3500131 Apr 08 '14 at 04:25
  • @user3500131, The loop only helps you move from x = -1 to x = 3. If you want to do lowest, you should think about how you are doing highest (in the if statement) and change that to get the smallest value instead of the largest. – merlin2011 Apr 08 '14 at 04:27