Newton's Method Java - java

Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the
x1=x0-f(x0)/f(x0) also needs a loop
Here's my code currently :
import java.util.Scanner;
public class NewtonsMethod {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your guess for the root:");
double x = keyboard.nextDouble();
double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
for(x=x-f(x)/f(x));
System.out.println("Your answer is:" + guessRootAnswer);
}
}

You've misstated how newton's method works:
The correct formula is:
xn+1 <= xn-f(xn)/f '(xn)
Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.
If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.
The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:
class Newton {
//our functio f(x)
static double f(double x) {
return Math.sin(x);
}
//f'(x) /*first derivative*/
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Stop if you're close enough
int max_count = 200; // Maximum number of Newton's method iterations
/* x is our current guess. If no command line guess is given,
we take 0 as our starting point. */
double x = 0;
if(argv.length==1) {
x= Double.valueOf(argv[0]).doubleValue();
}
for( int count=1;
//Carry on till we're close, or we've run it 200 times.
(Math.abs(f(x)) > tolerance) && ( count < max_count);
count ++) {
x= x - f(x)/fprime(x); //Newtons method.
System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
}
//OK, done let's report on the outcomes.
if( Math.abs(f(x)) <= tolerance) {
System.out.println("Zero found at x="+x);
} else {
System.out.println("Failed to find a zero");
}
}
}

Related

Take Average of an Array using Recursion

I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}

Find Average using Array of Objects/Object Array

this is such a simple problem but for some reason, I cant wrap my head around Array of Objects or Object Arrays. All I have to do is take in 5 user inputs, and create a class called Height, create object array and store user inputs into obj array and print the average. I'm kinda stuck.
class Height{
int total=0;
int count=0;
public Height(int y) {
total=total+y;
count++;
}
public void print() {
System.out.print("The average is: "+total/count);
}
}
public class ObjectArray {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter 5 heights in inches: ");
int[] x=new int[5];
int total=0;
for(int i=0;i<x.length;i++) {
x[i]=s.nextInt();
}
Height[] h=new Height[x.length];
for(int y=0;y<x.length;y++) {
h[y]=new Height(x[y]);
}
h.print();
}
}
Maybe I'm over complicating it. The problem right now is that I cannot invoke h.print();. I've tried different iterations, ex: taking out the print method and doing all the printing after every iteration.
Your approach is wrong. Your Height class appears to be responsible for the evaluation of the mean value. Hence, you should put all values inside a single Height instance, instead of generating a new instance for each user value.
However, h is an array of Heights object, while print() method is defined on a single Height instance. In order to call such method, you have to access one of the objects contained in h, that is h[0].print().
I'm assuming that your goal is simply to print the average of all the heights recieved via user input.
Your code in your main method is a tad confusing, so correct me if I'm wrong in any of the examples I give here. You should, instead of creating the x[] array, simply add the user input for the five values to Height.total in a for loop, and increase the Height.count variable by one each loop through. This should look something like this:
for (int i = 1; i <= 5; i++) {
// System.out.println("Please enter the next height: ");
Height.total += s.nextDouble();
Height.count++;
}
Then, you can run Height.print();.
I would also recommend adding a System.out.print(""); command to let the user know that they should enter the next value. That's the comment I left in the example code I gave above.
You have to design your Height in a way that match your requirement :
you need different Height with for each one a value
you need to know how many instances there is
For that, you need a private value, and a static counter :
class Height {
private int value = 0;
private static int count = 0; // static => nb of instances
public Height(int y) {
value = y;
count++;
}
public static int averageOf(Height... heights) {
return Arrays.stream(heights).mapToInt(h -> h.value).sum() / count;
}
}
To get the average, because it doesn't depend on a particular instance, you can have a static method, that sums all the value of the Height given and divide by the nb of instance
And use like :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int nb = 5;
System.out.println("Enter " + nb + " heights in inches: ");
Height[] heights = new Height[nb];
for (int i = 0; i < heights.length; i++) {
heights[i] = new Height(Integer.parseInt(s.nextLine()));
}
System.out.println("Average is " + Height.averageOf(heights));
}

Little coding challenge (Fermat’s Last Theorem)

I am trying to learn Java; here is the exercise I am struggling with:
Fermat’s Last Theorem says that there are no integers a, b, and c such that a^n + b^n = c^n except in the case when n = 2.
Write a method named checkFermat that takes four integers as parameters— a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that a^n + b^n = c^n, the program should print “Holy smokes, Fermat was wrong!” Otherwise the program should print “No, that doesn’t work.”
You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example:
int x = raiseToPow(2, 3);
would assign the value 8 to x, because 2^3 = 8.
I have encountered several problems, for example I can't seem to use Math.Pow(a, n) with an int, only with a double. If you are interested, here is what I have so far, feel free to skip it and just write your own version of the program in the answers.
(Please keep in mind I started this book only a few days back.)
package fermat.s_last_theorem;
import java.lang.Math;
import java.util.Scanner;
public class FermatS_Last_Theorem {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("Inster First Number");
double frst = s.nextDouble();
System.out.println("Insert Second Number");
double scnd = s.nextDouble();
System.out.println("Insert Exponent");
double expo = s.nextDouble();
double v = FLaw(frst,scnd,expo);
double k = FLawRes(v, expo);
System.out.println("The answer is " + v);
System.out.println("Your answer rooted by your exponent is " + k);
Law(v, Pow(k, expo));
}
public static double Pow(double a, double b) {
double res = Math.pow (a, b);
return (res);
}
public static double FLaw(double frst, double scnd, double expo) {
double D1 = Pow(frst, expo);
double D2 = Pow(scnd, expo);
return (D1 + D2);
}
public static double FLawRes(double res, double base) {
double D3 = Pow(res, 1/base);
return D3;
}
public static void Law(double v, double k) {
if (v==k) {
System.out.println("Pythagora works.");
} else {
System.out.println("Pythagora doesnt work");
}
}
}
The main problem is that I am not exactly sure how to answer the question the exercise asks, and the program listed above does not work as it should.
You should assume that there is a method named raiseToPow ...
That means you write your code using such a method, even though you don't have the method. Your code will be reviewed manually, or teacher may supply the method and run your code.
If you want to test your code, you can always implement it yourself. You should just remove the method before turning in the code.
But the intent here is that this is a write-on-paper exercise.
Now, how to implement int raiseToPow(int a, int b)?
Think about what it means. 34 means 3 * 3 * 3 * 3.
So, implement the method to multiply by a by itself b times.
I'll leave that as another exercise for you.
You can break it out like this :
public boolean checkFermat(int a, int b, int c, int n) {
if(n != 2 &&
(checkFermatCondition(a,b,c,n) ||
checkFermatCondition(a,c,b,n) ||
checkFermatCondition(b,c,a,n))) {
System.out.println("Holy smokes, Fermat was wrong!");
} else {
System.out.println("No, that doesn’t work.");
}
}
In this method you are just trying to reduce you check condition with all of the combinations by calling this method with different parameters
private boolean checkFermatCondition(int a, int b, int c, int n) {
return raiseToPow(a,n)+raiseToPow(b,n) == raiseToPow(c,n);
}
Your function raiseToPow()'s functionality can be achieved using Math.pow:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println( "Fermat's Last Theorem: a^n+b^n != c^n (n!=2)");
int a, b, c, n;
System.out.print("Enter value for a:");
a = s.nextInt();
System.out.print("Enter value for b:");
b = s.nextInt();
System.out.print("Enter value for c:");
c = s.nextInt();
while(true){
System.out.print("Enter value for n:");
n = s.nextInt();
if(n!=2)
break;
System.out.println("n cannot be 2");
}
checkFremat(a,b,c,n);
}
public static void checkFremat(int a, int b, int c, int n){
if ((int)Math.pow(a, n)+(int)Math.pow(b, n)!=(int)Math.pow(c, n))
System.out.println("Fermat was correct!");
else
System.out.println("Holy smokes, Fermat was wrong!");
}
}
Try it here!

Java square root calculator?

Ok, I'm a beginner in java, learning on my own through websites and books. I tried a simple square root calculator with a for loop and a while loop (I've included what I tried below). Sadly, all my code does when I enter a number is terminate. Any help would be appreciated!
import java.util.Scanner;
public class The2RootProdject {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double rootIt = input.nextDouble();
double dummy = 0.0000000;
while (dummy != dummy * dummy) {
dummy += 0.0000001;
if (rootIt == dummy * dummy) {
System.out.println("the squar root of " + rootIt + " is "
+ (dummy * dummy));
}
}
}
}
You have a couple of problems here:
1) Logical bug: 0 == 0 * 0
<= This means while (dummy != dummy * dummy) {..} will never be untrue, and you'll never even enter the loop
2) Floating point numbers are inexact, so your algorithm (which relies on "==") might not work anyway
Look here for more details on floating point imprecision:
http://www.lahey.com/float.htm
This is true for ANY language - your algorithm for square root must take this into account.
Try to use this algorithm which use Newton's iteration:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
double number, t, squareRoot;
Scanner input = new Scanner(System.in);
number = input.nextDouble();
squareRoot = number / 2;
do
{
t = squareRoot;
squareRoot = (t + (number / t)) / 2;
}
while ((t - squareRoot) != 0);
System.out.println(squareRoot);
}
}
Newton's iteration is an algorithm for computing the square root of a number via the recurrence equation:
X(n+1) = (X(n) + number/X(n))/2
I think the while condition is supposed to be =
while(rootIt != dummy * dummy) {}
Your current condition will only ever be true if you initialized dummy as 1; but I don't that would be what you want anyways.

How to call up calculations in custom methods to main Method

I have a main method and 4 other function type methods which include calculations, however, How would I call each one up into the main and proceed to print out the calculations. Also I am currently getting a lot of syntax errors.
I've tried placing brackets and braces when needed, however, that has just resulted into more errors. Also, I tried initializing Strings and integers elsewhere, which still seems to fail to work. Any help would be much appreciated!
Some syntax errors include: ';' expected on line 60
insert ';' to complete localVariableDelcartion on line 60
these errors are repeated for every line
import java.io.*;
//create the class
public class CirclemethodsFixedagain
{
//main method
public static void main(String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
// more user questions
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
System.out.println("*NOTE* Pressing a key outside of this range or a regular character will re-prompt the original message");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
// more user questions
System.out.println("Now enter the radius of the required shape(Half of diameter)");
System.out.println("*NOTE* Pressing a regular character will re-prompt the original message");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
}
//user created method, with each
public static int circlemethods(double circumference) throws IOException {
{
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
circumference = (Math.PI) * (2) * (num);
System.out.print("The circumference of that sphere is :");
return circumference;
}
public static double circlemethods2 (double area) throws IOException
{
if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
area = (Math.PI * num * num);
System.out.print("The area of the circle is :");
return area;
}
}
public static double circlemethods3 (double volume) throws IOException
{
if (numInput == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
volume = (4 * Math.PI * num * num * num) / 3 ;
System.out.print("The volume of that sphere is : cm³");
return volume;
}
}
public static double circlemethods4 (double surfaceArea) throws IOException
if (numInput == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
surfaceArea = 4 * Math.PI * num * num;
System.out.print("The Surface area of that sphere is :");
return surfaceArea;
}
}
}
}
Your braces - the { and } characters - don't match up. I have fixed the indentation of the code in the question so that you can better see where the problem gets started - in the method circlemethods. Also, circlemethods4 is missing its braces.
Keeping consistent indentation levels throughout the program makes these kinds of errors a lot more obvious to spot.
Compilation errors are caused by:
You can not place methods inside other method, move circlemethods 2,3,4 outside the circlemethod1.
Your circlemethods don't see numInt local variable. It is declared in main method and it is visible only in that one.
I believe you don't need if statements at the begining of each circlemethods. You rather need something like that:
if (numInt == 1)
{
circlemethod1(radius);
} else if (numInt == 2) {
circlemethod2(radius);
}
etc. in your main method.
You can also change argument's name of each circlemethod, as I understood it is always radius. Current name of arguments is a good candidate for method name.
Following are the inputs that will fix the problem :
You can't declare method inside a method, It's not JAVA syntax. Just check the bracing correctly. Use any IDE for doing the same.
Make numInt, num as static (Class) variables. As you are using those in static method.
Use proper names and camelCasing nomenclature to name any method.
|e.g calculateCircleArea(), calculateCircleVolume(), etc..
Hope this solves your problem.

Categories

Resources