Beginner's Java Code Help: Newton Raphson Square Root Loop - java

In my Java class for college we are learning about the Looping control structure, and we got an assignment to code a little program that I am guessing is supposed to give the square root of a number and keep on taking the square root until the difference or accuracy is met. Here are the instructions:
"Write a class called NewtonRaphson that can be used to find an approximate solution of sqrt(a) using Newton's method, for any positive real number.
Note: sqrt(a) can be expressed in functional notation as follows: f(x) = x2 – a,
From which f ' (x) = 2 * x,
Print the iteration sequence and the approximation for each iteration. (That is, in a tabular form).
Write a driver class called TestNewton. Use the following data to test the class NewtonRaphson.
• The initial guess is 5.0
• In this exercise, the process terminates when the difference between two consecutive approximations is less than 0.00005"
I have my code linked at the bottom here, the main class and the test class, but I am not getting the looping result I am just getting the same square root of 5 when I type in 5 after running the program. Can someone please tell me where I messed up on?
Thanks, I am really new to coding, and this took forever to make and I had to ask for some friends help.
Main Class: http://pastebin.com/eiUJFJjQ
Test Class: http://pastebin.com/sJ4dB5uZ
Or if you prefer the code here it is:
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class NewtonRaphson {
static final double DIFFERENCE = 0.00005;
double n;
double x;
double derivative;
double function;
double xold;
double xnew;
int i;
public NewtonRaphson(double n2, int x2)
{
n=n2;
x=x2;
function = Math.pow(n, 2)-x;
derivative = 2*n;
xnew=n-function/derivative;
xold=0;
}
boolean positive()
{
return (n >= 0);
}
public double findXNew(double xold2)
{
function = Math.pow(xold2, 2)-x;
derivative = 2*xold2;
return xold2-function/derivative;
}
public void findSqRtA()
{
i=0;
while(Math.abs(xnew-xold)> DIFFERENCE)
{
xold=xnew;
xnew=findXNew(xold);
i++;
System.out.println(this);
}
System.out.println("\nIteration completed, difference is less than 0.00005");
}
public String toString()
{
NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("0.00000000");
return "The approximate value of the square root of "+x+" is " + xnew + "\n" +
"The number of iterations is " + i;
}
}
and
import java.io.Console;
import java.util.Scanner;
public class TestNewton {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number you would like to find the square root of");
int a = reader.nextInt();
NewtonRaphson nr = new NewtonRaphson(5.0, a);
nr.findSqRtA();
}
}
My output is this, but I want it to take the square root after each iteration's result.
Enter a number you would like to find the square root of
5
The approximate value of the square root of 5.0 is 2.3333333333333335
The number of iterations is 1
The approximate value of the square root of 5.0 is 2.238095238095238
The number of iterations is 2
The approximate value of the square root of 5.0 is 2.2360688956433634
The number of iterations is 3
The approximate value of the square root of 5.0 is 2.236067977499978
The number of iterations is 4
Iteration completed, difference is less than 0.00005

Newton-Raphson method is very interesting. You can use it to approximate real-valued function roots. x2 is only one of them. Check this fractals produced with Newton-Raphson method. So, do not underestimate Newton-Raphson.
Your code works. But your expectations are mistaken, you think that on every iteration you will update the guess. The code actually does it in the while loop.
You may do something like this, the epsilon may also be a parameter.
First, you give a large epsilon find a square root estimation.
Then input the last approximation with a slightly smaller epsilon, until you are satisfied with the result.
I think this is what you expect.
You can simplify the code. Check this code out.

Your code is actually producing the correct result for me. Therefore I'm not sure what the problem is.
For help with Newton's method you can refer to this article:
http://en.wikipedia.org/wiki/Newton's_method
Can you show us your output?
"I thought the program is supposed to take the square root of each new answer from the previous square root, it constantly takes the square root of 5. But I want it to take the square root of each iteration's result"
Oh, I see, that's because you have this:
NewtonRaphson nr = new NewtonRaphson(5.0, a);
Simply replace the 5.0 above with your previous number.

Related

How can we solve NaN conflict in java?

`java
//5. Write a program to read three sides of triangle and print area for valid data and to print “Invalid data”
// if either one side of the triangle is greater or equals to the sum of other two sides.
package com.company;
import java.util.Scanner;
import java.lang.Math;
public class EX_05 {
public static void main(String[] args) {
Scanner n = new Scanner(System.in);
System.out.println("Enter three sides of a triangle : ");
double a = n.nextDouble();
double b = n.nextDouble();
double c = n.nextDouble();
double s = (a+b+c)/2;
if((a>=(b+c)) || (b>=(a+c)) || (c>=(b+a)) ){
double area = Math.pow((s * (s - a) * (s - b) * (s - c)), 0.5);
System.out.println("The area of triangle is " + area + ".");
}
else {
System.out.println("Invalid data");
}
}
}
`
I wanted to conclude whether the sides of triangle is valid or not to calculate area of triangle.
Here is the output shown by IDE.
Looks like your condition is inverted. You always perform the calculation if the data is invalid and always print "invalid data" if the data is valid.
You should switch what you have in the else with what you have in the if.
Another option would be to add a ! in front of the entire condition.
Yet another would be to invert the logic of the entire condition.
Beyond that, the title of your question is completely unrelated to the actual problem. And please don't paste images of code. They hate that here on stack overflow. Its no fun re-typing all of someone's buggy code on your own machine just to help them find the problem. Post the code itself so it can be easily copied and tested.
Your condition, to check whether the sides form a valid triangle, is wrong. Please correct that and you should get a proper value for area.

Getting the inverse of a function that uses summation in Java

I have a program with one class, which looks like this.
public class Functions {
public static void main(String[] args) {
System.out.println(summationFunction(1)); //Prints 13
System.out.println(summationFunction(2)); //Prints 29
System.out.println(summationFunction(3)); //Prints 48
System.out.println(summationFunction(4)); //Prints 70
}
public static int summationFunction(int input) {
int summedNumber = 0;
int i = input;
while (i > 0) {
summedNumber += i * 3;
i--;
}
return 10 * input + (summedNumber);
}
}
So, this program will take in a given number and apply this function to it:
And this all works well (I have run the class Functions and everything prints just as it's supposed to.) BUT, I need to find the inverse of this function, and I need to be able to translate it to code; I do not know how to do this.
I basically need a function that will return values like this:
public static void main(String[] args) {
System.out.println(summationFunction(13)); //Prints 1
System.out.println(summationFunction(29)); //Prints 2
System.out.println(summationFunction(48)); //Prints 3
System.out.println(summationFunction(70)); //Prints 4
}
which, (as you can tell) is the opposite of the original function.
So to sum everything up, I need a function that will return the inverse of my original function (summationFunction), and I would like to know how I would model this or if there is a quick solution, in code.
One more thing: I know that I can have the method take an input and search for the most similar output of the original method, but I would like to see if there is a simpler way to do this which does not involve searching, thus giving a quicker output speed. And if you wish you can safely assume that the input of the inversed function will always be a number which will give an integer output, like 13, 29, 48, 70, etc...
By the way, if you are going to downvote the question, will you at least give a reason somewhere? The comments perhaps? I can not see any reason that this question is eligible for being downvoted, and a reason would help.
Wolfram Alpha to the rescue !
It tells you that this function can be written as :
1/24*(6*x+23)^2-529/24
So if you want to solve f(x)=a, you have :
x = 1/6*(sqrt(24*a+529)-23)
a = 70
# => x = 4
Note : Using Wolfram shouldn't prevent you from finding the answer on your own.
sum(something*i) is equal to something*sum(i) because something (3 in this case ) doesn't depend on i.
sum(i,i=1..n) is equal to n*(n+1)/2, and it's easy to prove (see Wikipedia)
So your function becomes 10*x+3*x*(x+1)/2
Expanded, it is :
(3 x^2)/2+(23 x)/2
You need to solve (3 x^2)/2+(23 x)/2 = 70, in other words :
(3 x^2)/2+(23 x)/2 - 70 = 0
It is a quadratic equation, with a=3/2, b=23/2 and c=-70 or c=-29 or c=....
You sum can be written like this 3*x*(x+1)/2 so you have equation 10*x + 3*x*(x+1)/2 = y you need to solve it.
Wolfram alpha tells that result will be 1/6.0 * (-23.0+sqrt(529.0+24.0 * y))

Arcsine does not change value for variable in Java

I've looked at various sites to try to solve my problem. I've also tried to look for any YT or other videos on trig in Java, but couldn't find anything. (I'm a noob, so I also don't always understand everything that most sites refer to).
Anyways, I'm trying to make a simple program to calculate parts of Snell's Law (I realize there are websites that do this). But arc-sine doesn't seem to affect my variable values at all
Here is the code:
import java.util.Scanner;
public class trig_functions_test {
public static void main(String[] args) {
Scanner HumanInput = new Scanner (System.in);
double n1, n2, Oi, OR;
System.out.println("Enter the first medium's index of refraction.");
n1 = HumanInput.nextDouble();
System.out.println("Enter the second medium's index of refraction.");
n2 = HumanInput.nextDouble();
System.out.println("Enter the angle of incidence.");
Oi = HumanInput.nextDouble();
System.out.println("Enter the angle of refraction.");
OR = HumanInput.nextDouble();
//if angle of refraction is the missing variable
if (OR == 0) {
Oi = Math.toRadians(Oi);
OR = (n1*Math.sin(Oi)/n2);
OR = Math.toRadians(OR);
OR = Math.asin (OR);
OR = Math.toDegrees(OR);
System.out.println(OR);
}
}
}
When I debug the program I get this:
First, here is the program in action:
(the 0 is just to signify no angle of refraction)
These are the results after the 2nd line in the if statement is evaluated(?):
After "OR" is converted to radians, the value of "OR" becomes 0.011364657670640462.
Then, and here is the problematic part, the part with the arc-sine is evaluated, and "OR" becomes 0.011364*90231927541* (the changed part is indicated between the *'s)
And then finally, "OR" is converted to degrees once more, and I am reverted back to my value after the second line (more or less) "OR," is then equal to 0.6511*609374816383* (again, the changed part is indicated between the *'s).
Your trouble stems from this line:
OR = Math.toRadians(OR);
You already have your answer in radians when you do this calculation:
OR = (n1*Math.sin(Oi)/n2);
When you convert it to radians again, you are skewing the result. Delete OR = Math.toRadians(OR); and your program will work as intended.
You're making your solution much more complicated than it needs to be. You should evaluate your expression in one shot by solving for the angle of refraction in Snell's law, like so:
Oi = Math.toRadians(Oi);
OR = Math.asin((n1/n2)*Math.sin(Oi));
OR = Math.toDegrees(OR)
System.out.println("Angle of refraction: "+OR);

Finding roots of quadratic equation using a specific class

i have this assignment that asks me to write a code that determines the roots of a quadratic equation (ax^2 + bx + c = 0). but i have to use the university's library (type.lib.Equation;).
i almost got everything figured out, except the case where there are two roots. i can get the 1st root but i'm still circling around to get the the 2nd root
my code so far
import java.util.Scanner;
import java.io.PrintStream;
import type.lib.Equation;
public class Check05A
{
/**
* #param args
*/
public static void main(String[] args)
{
PrintStream output = System.out;
Scanner input = new Scanner(System.in);
output.println("Enter a,b,c pressing ENTER after each... ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
output.print("The equation: ");
Equation x = new Equation(a, b, c);
output.print(x);
int root = x.getRootCount();
if(root == 0)
{
output.println(" has no real roots.");
}
if(root == 1)
{
double r1 = x.getRoot(root);
output.println(" has the single root: " + r1);
}
if(root == 2)
{
double r1 = x.getRoot(root);
double r2 = -x.getRoot(root);
output.println(" has the two roots: " + r2 + " and " + r1);
}
if(root == -1)
{
output.println("\nis an identity - any value is a root.");
}
}
}
for example 1, 2, -4 should output as :
"has the two roots: -3.23606797749979 and 1.2360679774997898"
You're just putting negative sign to root 1.
This isn't always the case.
Look up the formula for finding the roots for a quadratic equation:
x=\frac{-b \pm \sqrt {b^2-4ac}}{2a}.
and inside your function x.getRoot(), return two values inside an array.
*Please note that this answer is for only TI-84 calculators using If statements to find the roots of any nth degree polynomial. If this does not answer the question for you, please move on.
I made a TI-84 program that is helpful to find the roots of any nth degree polynomial. Here is the code:
(note that Z and S were set to be the derivatives of f and g; you have to find these yourself (I will update this code later with a parameter where it will get f' and g' by itself. Set z and s to 1 to use it to find GCF or roots!) (Also, Y1 is found in vars, if you tab right after clicking vars button, pressing enter, then enter again)
To start, put the function/s that you are working with into Y1, Y2, etc...
enter code here :Prompt F,G`:Prompt Z:Prompt S:If Y1=F:If Y2=G:F*G=FS+GZ->H :If X≥Y:X-Y=I->I:Disp I:If I=0:If I>0:Repeat X-Y=J->J:Disp J
That's it! Super simple, but so helpful! Let me know of any improvements (I am going to make a derivative finder program soon to embed into this code soon!)
Thanks so much, and have fun with the code! -Evan

proper way to store large numbers in a variable

I would like to play around with numbers and however elementary, Ive been writing algorithms for the fibonacci sequence and a brute force path for finding prime numbers!
Im not a programmer, just a math guy.
However, a problem I run into quiet often is that a long long, double and floats often run out of room.
If I wanted to continue to work in JAVA, in what way can I create my own data type so that I dont run out of room.
Conceptually, I thought to put 3 doubles together like so,
public class run {
static double a = 0;
static double b = 0;
//static double c = 0;
static void bignumber(boolean x) {
if (x == true && a < 999999999) {
++a;
} else if (x == true && a == 999999999) {
++b;
a = 0;
}
System.out.print(b + "." + a + " \n");
}
public static void main(String[] args) {
while(true) {
bignumber(true);
}
}
}
is there a better way to do this,
I would like to one day be able to say
mydataType X = 18476997032117414743068356202001644030185493386634
10171471785774910651696711161249859337684305435744
58561606154457179405222971773252466096064694607124
96237204420222697567566873784275623895087646784409
33285157496578843415088475528298186726451339863364
93190808467199043187438128336350279547028265329780
29349161558118810498449083195450098483937752272570
52578591944993870073695755688436933812779613089230
39256969525326162082367649031603655137144791393234
7169566988069
or any other number found on this site
I have also tried
package main;
import java.math.BigInteger;
public class run {
BigDecimal a = 184769970321174147430683562020019566988069;
public static void main(String[] args) {
}
}
But it still seems to be out of range
Use BigDecimal (instead of double), and BigInteger (instead of int, long) for that purpose, But you can only work with them by their methods. No operators, can be used.
Used like this:
BigInteger big = new BigInteger("4019832895734985478385764387592") // Strings...
big.add(new BigInteger("452872468924972568924762458767527");
Same with BigDecimal
BigDecimal is the class used in java where you need to represent very large or very small numbers, and maintain precision. The drawbacks are that it is not a primitive, so you can't use the normal math operators (+/-/*/etc), and that it can be a little processor/memory intensive.
You can store large numbers like this:
length
digits[]
and implement your math for them. This is not very complicated. As a hint, to make everything more simple you can store the digits in reverse order. This will make your math simpler to implement - you always add nr[k] with nr[k] and have room for transport for any length numbers, just remember to fill with 0 the shorter one.
In Knuth Seminumeric Algorithms book you can find a very nice implementation for all operations.

Categories

Resources