Last active
September 2, 2020 09:42
-
-
Save mlsmrc/136076444e1c4cef5b152f383b1d1a7d to your computer and use it in GitHub Desktop.
Erone method to build the square root of a given number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.JOptionPane; | |
public class SquareRoot { | |
private int attempts=0; | |
private double x=0,epsilon = 0; | |
public SquareRoot(int x,double epsilon,int attempts) | |
{ | |
this.x=(double)x; | |
this.epsilon=epsilon; | |
this.attempts=attempts; | |
} | |
public void run() | |
{ | |
int tot_attempts=attempts; | |
double x_n = Math.random()*x; | |
double x_n_1 = 0; | |
while(attempts-- >0 && Math.abs(x_n-x_n_1)>epsilon) | |
{ | |
x_n_1 = x_n; | |
x_n = 0.5 * (x_n_1 + x/x_n_1); | |
} | |
JOptionPane.showMessageDialog(null, "Square root of "+x+" = "+x_n+"\n"+"# Attempts = "+(tot_attempts-attempts),"Result", JOptionPane.INFORMATION_MESSAGE); | |
} | |
public static void main(String[] args) { | |
int a = Integer.valueOf(JOptionPane.showInputDialog("Inserire il numero")); | |
double e = Double.valueOf(JOptionPane.showInputDialog("Distanza dalla valore radice")); | |
int t = Integer.valueOf(JOptionPane.showInputDialog("Numero di tentativi")); | |
new SquareRoot(a, e, t).run(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment