UIUC SOC 100 - Newton 1and 2

Unformatted text preview:

Newton1and2.java Thursday, January 27, 2022, 2:40 PM1 import components.simplereader.SimpleReader;56 /**7 * Calculate the square root an inputed number with a given error range that is8 * compatible with 0.9 *10 * @author Chime Nwaru11 *12 */13 public final class Newton1and2 {1415 /**16 * Private constructor so this utility class cannot be instantiated.17 */18 private Newton1and2() {19 }2021 /**22 * Computes estimate of square root of x to within relative error 0.01%.23 *24 * @param x25 * positive number to compute square root of26 * @return estimate of square root27 */28 private static double sqrt(double x) {2930 /*31 * Finds the square root of the given number by going from 0 to the32 * given number and seeing if that number squared is within .0001 of the33 * given number34 */35 final double error = .0001;36 double range = x;37 /*38 * The code goes through every possible value from 0.0 to x+1 (the plus39 * 1 accounts for the square root of number between 0 and 1) and keeps40 * the first value that gives answer that's within the error range41 */42 for (double i = 0.0; i < x + 1; i = i + error) {43 if (Math.abs(i * i - x) < Math.abs(range * range - x)) {44 range = i;45 }4647 }4849 return range;5051 }5253 /**54 * Put a short phrase describing the static method myMethod here.55 */5657 /**58 * Main method.59 *60 * @param argsPage 1Newton1and2.java Thursday, January 27, 2022, 2:40 PM61 * the command line arguments62 */63 public static void main(String[] args) {64 SimpleReader in = new SimpleReader1L();65 SimpleWriter out = new SimpleWriter1L();66 /*67 * Put your main program code here; it may call myMethod as shown68 */6970 /*71 * Asks for the user to input the number a number to find the square72 * root of73 */74 out.print("What number do you want to find the square root of: ");75 double x = in.nextDouble();7677 /*78 * Calls the sqrt method and prints out the square root79 */80 double root = sqrt(x);81 out.print("The square root is " + root);82 /*83 * Close input and output streams84 */85 in.close();86 out.close();87 }8889 }90Page

View Full Document

# UIUC SOC 100 - Newton 1and 2

Pages: 2
Documents in this Course Unlocking...