Question

In: Computer Science

In JAVA, please With the mathematics you have studied so far in your education you have...

In JAVA, please

With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to an equation f(x) = 0 for some function f. Use the bisection method. To solve the problem using this method first find two values of x, A and B, such that when evaluated in the function f(x) they give opposites signs for the y value. If f(x) is continuous between these two values then we know that there is at least one x which evaluates to a 0 y value, which is between these two values A and B. Treat the positive value as an upper bound and the negative value as a lower bound. Divide the space between A and B in half and evaluate the function at that new point.   If the value is positive than it replaces the existing upper-bound and if it is negative it replaces the existing lower-bound. Continue dividing the space between the upper-bound and lower-bound in half and evaluating this new value and generating new upper and lower bounds as the case may be. Continue the evaluation process until the x value that you are plugging into the function evaluates to a y value that is zero plus or minus .0000001.

                Consider the possibility of finding all the real roots of any given function up to and including x raised to the fifth power. Input should consist of reading the coefficients one at a time to the powers of x up to 5 and some constant.   Do a desk check with calculator on y = X2 -2 and identify the variables associated with that problem. Write the code that follows your algorithm. Then test your program on other polynomials such as 2x5 -15x4 + 35x3 -15x2-37x + 30 (roots are -1, 1, 2, 2.5, 3) and 3x5 -17x4 + 25x3 + 5x2 -28x + 12 (roots are -1,1, 2/3, 2, 3). Use at lest 3 methods. One to read the 5 coefficients, one to calculate the value of the polynomial and one to do the binary bisection search.   Use the following for loop to work through the X values:for(double x = -5.0000001; x < 5.0000001; x = x + .1)

After it runs as a console program, using the GUI example from my website as a guide, convert this program to a graphics program. Keep the example GUI always working. Create multiple versions as you add code that will implement the polynomial problem. Always be able to go back to a previous working version if you get stuck. When you get the polynomial program working then delete the example code. To debug your compiled program, use System.out.println() to follow intermediate values of your variables to see where your code does not follow the algorithm.

----------------------- example
/**
 * demonstrating a GUI program
 */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ExampleGUI extends JPanel
{
        // ***Variables are created ***
        //*** GUIs are made up of JPanels.  Panels are created
        //*** here and named appropriately to describe what will
        //*** be placed in each of them.
        JPanel titlePanel = new JPanel();
        JPanel questionPanel = new JPanel();
        JPanel inputNumberPanel = new JPanel();
        JPanel addAndSubtractButtonPanel = new JPanel();
        JPanel answerPanel = new JPanel();
        JPanel nextNumberPanel = new JPanel();
        //*** a JLabel is a text string that is given a String value
        //*** and is placed in its corresponding JPanel or JButton
        JLabel titleLabel = new JLabel();
        JLabel questionLabel = new JLabel();
        JLabel inputNumberLabel = new JLabel();
        JLabel add5Label = new JLabel();
        JLabel subtract5Label = new JLabel();
        JLabel answerLabel = new JLabel();
        JLabel nextNumberLabel = new JLabel();
        //*** three JButtons are created.  When pushed, each button calls
        //*** its corresponding actionPerformed() method from the class created
        //*** for each button. This method executes the method code, performing
        //*** what the button is to do.
        JButton add5Button = new JButton();
        JButton subtract5Button = new JButton();
        JButton nextNumberButton = new JButton();
        //*** a JTextField creates a location where the client can place
        //*** text
        JTextField inputTextField = new JTextField(15);

        
         //*** constructor
         //*** Variables are given initial values
        
        public ExampleGUI()
        {
                //*** set panel layouts
                //*** panels could be LEFT, or RIGHT justified.
                titlePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                questionPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                inputNumberPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                addAndSubtractButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                answerPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                nextNumberPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

                //*** set Label fonts.  You can use other numbers besides 30,20
                //*** or 15 for the font size.  There are other fonts.
                Font quizBigFont = new Font("Helvetica Bold", Font.BOLD, 30);
                Font quizMidFont = new Font("Helvetica Bold", Font.BOLD, 20);
                Font quizSmallFont = new Font("Helvetica Bold", Font.BOLD, 15);
                titleLabel.setFont(quizBigFont);
                questionLabel.setFont(quizMidFont);
                inputNumberLabel.setFont(quizMidFont);
                add5Label.setFont(quizSmallFont);
                subtract5Label.setFont(quizSmallFont);
                answerLabel.setFont(quizBigFont);
                nextNumberLabel.setFont(quizSmallFont);
                inputTextField.setFont(quizMidFont);
                //*** labels are given string values
                titleLabel.setText("Add or Subtract Five");
                questionLabel.setText("Please enter an integer number.");
                inputNumberLabel.setText("Number:");
                add5Button.setText("   Add 5   ");
                subtract5Button.setText("Subtract 5");
                answerLabel.setText("");
                nextNumberButton.setText("   New Number   ");
                //*** the 3 buttons are connected to their classes
                add5Button.addActionListener(new add5Button());
                subtract5Button.addActionListener(new subtract5Button());
                nextNumberButton.addActionListener(new nextNumberButton());
                //*** Labels, buttons and textFields are added to their
                //*** panels
                titlePanel.add(titleLabel);
                questionPanel.add(questionLabel);
                //*** inputNumberPanel has 2 items added
                inputNumberPanel.add(inputNumberLabel);
                inputNumberPanel.add(inputTextField);
                //*** submitPanel has two items added
                addAndSubtractButtonPanel.add(add5Button);
                addAndSubtractButtonPanel.add(subtract5Button);
                answerPanel.add(answerLabel);
                nextNumberPanel.add(nextNumberButton);
                //*** The panels are added in the order that they should appear.
                //*** Throughout the declarations and initializations variables were
                //*** kept in this order to aid in keeping them straight
                setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                add(titlePanel);
                add(questionPanel);
                add(inputNumberPanel);
                add(addAndSubtractButtonPanel);
                add(answerPanel);
                add(nextNumberPanel);
                
                 //*** The method writeToFile() is called from the constructor.
                 //*** One could call a read method from the constructor.
                
        //      writeToFile();
        }// constructor
        
         //*** This method writes 4 lines to a file.  Eclipse puts the file in
         //*** the folder of the project but not in the src folder.  Put any
         //*** file that you want read in the same place so that Eclipse can
         //*** find it.
        /* 
        private void writeToFile()
        {
                String fileName = "textFile.txt";
                String line = null;
                int count;
                Scanner scan = new  Scanner(System.in);
                PrintWriter textStream = TextFileIO.createTextWrite(fileName);
                System.out.println("Enter 4 lines of text:");
                for (count = 1; count <= 4; count++)
                {
                        line = scan.nextLine();
                        textStream.println(count + " " + line);
                }
                textStream.close( ); //*** did not require error handling
                System.out.println("Four lines were written to " + fileName);
        }
        */
         //*** display() is called from main to get things going
         
        public void display()
        {       //*** A JFrame is where the components of the screen
                //*** will be put.
                JFrame theFrame = new JFrame("GUI Example");
                //*** When the frame is closed it will exit to the
                //*** previous window that called it.
                theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //*** puts the panels in the JFrame
                theFrame.setContentPane(this);
                //*** sets the dimensions in pixels
                theFrame.setPreferredSize(new Dimension(600, 380));
                theFrame.pack();
                //*** make the window visible
                theFrame.setVisible(true);
        }
        
         //*** method doSomething is called from an actionPerformend method
         //*** demonstrating calling methods that can do work for you.
         
        private void doSomething()
        {
                for(int x = 1; x <= 10; x++)
                        System.out.println(" in doSomething method x is " + x);
        }

        
        //*** This class has one method that is called when the add5Button
        //*** is pushed.  It retrieves the string from the JTextField
        //*** inputTextField, converts it to an integer and manipulates the
        //*** number.
        //*** NOTE: a string of integers can be formed by creating a string
        //*** with one of the numbers and then concatenating the other integers
        //*** to form the string.
         
        class add5Button implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        System.out.println(" in add5Button class");
                        doSomething();//*** other methods can be called
                        int number = Integer.parseInt(inputTextField.getText());
                        number = number + 5;
                        String stringNumber = "" + number;
                        answerLabel.setText(stringNumber);//*** answerLabel gets a new value
                        inputTextField.setText(stringNumber);
                }
        }
        class subtract5Button implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        System.out.println(" in subtract5Botton class");
                        int number = Integer.parseInt(inputTextField.getText());
                        number = number - 5;
                        String stringNumber = "" + number;
                        answerLabel.setText(stringNumber);
                        inputTextField.setText(stringNumber);
                }
        }
        
        //*** this method resets the values of inputTextField and answerLable
         
        class nextNumberButton implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        inputTextField.setText("");//*** erases the values of this JTextField
                        answerLabel.setText("");//*** erases the value of this JLabel
                }
        }
        public static void main(String[] args) throws IOException
          {
                ExampleGUI gameGUI = new ExampleGUI();
                System.out.println("we can print to the console");
            gameGUI.display();

          }
}

Solutions

Expert Solution

CODE

import java.util.Scanner;

public class BetterBisection {
public static void main(String[] args) {
double a, b, c; // a, b and c have the usual meaning
double f_of_a, f_of_b; // f_of_a, f_of_b store values of f(a) and f(b)
// respectively
int highest_degree;
System.out.println("What is the highest degree of your polynomial? ");
Scanner input = new Scanner(System.in);
highest_degree = input.nextInt();
for (int i = highest_degree; i >= 0; i--) {
int coeff_deg_i;
coeff_deg_i = poly_input(i);
// System.out.println(coeff_deg_i);
}
// The following do-while loop keeps asking the user for a and b until
// f(a)f(b) does not become negative
do {
a = input();
b = input();
if (f(a) * f(b) >= 0) {
System.out
.println("Sorry the two numbers are not bracketing the root. Please try again ");
}
} while (f(a) * f(b) >= 0);
f_of_a = f(a);
f_of_b = f(b);
double root = bisectionMethod(f_of_a, f_of_b, a, b);
System.out.println("Root is : " + root);
}

public static double input() { // Reads in the bracketing number i.e a and b
Scanner input = new Scanner(System.in);
System.out.println("Enter a bracketing number");
return (input.nextDouble());
}

public static double f(double num) { // Calculates f(x) given x and returns
// f(x)
final int COEFF_DEG_3 = 1; // Coefficient of x^3
final int COEFF_DEG_2 = 4; // Coefficient of x^2
final int COEFF_DEG_0 = -10; // Coefficient of x^0
return (COEFF_DEG_3 * Math.pow(num, 3) + COEFF_DEG_2 * Math.pow(num, 2) + COEFF_DEG_0
* Math.pow(num, 0));
}

public static double bisectionMethod(double f_of_a, double f_of_b, double a,
double b) { // Does the actual work of evaluating
double c; // the root using the method of bisection.
double f_of_c;
final double TOLERANCE = 0.0001;
while (Math.abs(a - b) > TOLERANCE) {
c = (a + b) / 2;
f_of_c = f(c);
if (f_of_c * f(a) == 0 || f_of_c * f(b) == 0) {
return c;
} else if (f_of_c * f(a) > 0) {
a = c;
} else {
b = c;
}
}
return (a + b) / 2;
}

public static int poly_input(int degree) {
System.out.println("Please enter coefficient for degree " + degree);
Scanner input = new Scanner(System.in);
int coefficient;
coefficient = input.nextInt();
return coefficient;
}

}

Please raise a comment if you face any problem or want some changes on this or if you like it please UPVOTE my answere.


Related Solutions

In JAVA PLEASE With the mathematics you have studied so far in your education you have...
In JAVA PLEASE With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to an equation f(x) = 0 for some function f....
Ans In Java Please Homework 6-1 So far in this course, all of your programs have...
Ans In Java Please Homework 6-1 So far in this course, all of your programs have been written to be fully contained inside a single method named main. The main method is where Java begins execution of your program. In this assignment, you will coding other methods in addition to the main method. These additional methods will perform specific functions and, in most cases, return results. Write all your methods in a class named Homework6Methods.java Write a public static method...
One the basis of what you have studied so far, how would you distinguish the neoclassical...
One the basis of what you have studied so far, how would you distinguish the neoclassical investment function [Investment = f(cost of borrowed funds)] from that of Keynes [Investment = f(expected profit rate - the cost of borrowed funds)]? In other words, why would Say’s law which is a key feature of neoclassical macroeconomics, not work if the investment is a function of expected profits?
Which of the three ethical philosophies that we have studied so far imparts the greatest wisdom...
Which of the three ethical philosophies that we have studied so far imparts the greatest wisdom in your well-reasoned opinion? In answering this question, discuss the concrete implications that these theories have for particular issues in both personal and political ethics. Give the best reasons you can think of to justify your answers (for example, reasons that might persuade an open minded person who initially disagrees with you). (20 points <600 words) USE ARISTOTLE, THE HUMAN GOOD AND FUNCTION ARGUMENT
Please use the economics knowledge you have learned so far to analyze the case below. You...
Please use the economics knowledge you have learned so far to analyze the case below. You can propose your own questions and then answer them. Remember, there is no absolutely correct answer to this exercise. Its purpose is to provide you an opportunity to demonstrate your ability to think like an economist by applying economic principles to interpret the logic of a real-world phenomenon. The Fortunes of Delta Airlines Follow the Business Cycle Delta Airlines has grown into the world’s...
Please use the economics knowledge you have learned so far to analyze the case below. You...
Please use the economics knowledge you have learned so far to analyze the case below. You can propose your own questions and then answer them. Remember, there is no absolutely correct answer to this exercise. Its purpose is to provide you an opportunity to demonstrate your ability to think like an economist by applying economic principles to interpret the logic of a real-world phenomenon. Can Greece Function without Banks? In 2001, Greece and most other European countries abandoned their individual...
Please use the economics knowledge you have learned so far to analyze the case below. You...
Please use the economics knowledge you have learned so far to analyze the case below. You can propose your own questions and then answer them. Remember, there is no absolutely correct answer to this exercise. Its purpose is to provide you an opportunity to demonstrate your ability to think like an economist by applying economic principles to interpret the logic of a real-world phenomenon. Why Is JPMorgan Chase Laying Off Workers? Many workers lost their jobs during the 2007–2009 recession...
Please use the economics knowledge you have learned so far to analyze the case below. You...
Please use the economics knowledge you have learned so far to analyze the case below. You can propose your own questions and then answer them. Remember, there is no absolutely correct answer to this exercise. Its purpose is to provide you an opportunity to demonstrate your ability to think like an economist by applying economic principles to interpret the logic of a real-world phenomenon. Will Economic Reforms in Mexico Boost Economic Growth? More than 18,000 U.S. companies, including Fortune 500...
Please use the economics knowledge you have learned so far to analyze the case below. You...
Please use the economics knowledge you have learned so far to analyze the case below. You can propose your own questions and then answer them. Remember, there is no absolutely correct answer to this exercise. Its purpose is to provide you an opportunity to demonstrate your ability to think like an economist by applying economic principles to interpret the logic of a real-world phenomenon. Economic Growth and the Business Cycle at Corning, Inc. In 1851, Amory Houghton founded the company...
For this assignment, you will apply what you learned in analyzing Java™ code so far in...
For this assignment, you will apply what you learned in analyzing Java™ code so far in this course by writing your own Java™ program. The Java™ program you write should do the following: Accept user input that represents the number of sides in a polygon. Note: The code to do this is already written for you. If input value is not between 3 and 5, display an informative error message If input value is between 3 and 5, use a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT