Problems with square root approximations with loops program

i'm having some trouble with this program, this loop stuff is confusing me and i know i'm not doing this correctly at all. the expected values in the tester are not matching up with the output. i have tried many variations of the loop in this code even modifying the i parameter in the loop which i guess is considered bad form. nothing seems to work...
here is what i have for my solution class:
/** A class that takes the inputted number by the tester and squares it, and
*  loops guesses when the nextGuess() method is called. The epsilon value is
*  also inputted by the user, and when the most recent guess returns a value
*  <= epsilon, then the hasMoreGuesses() method should return false.
public class RootApproximator
   /** Takes the inputted values from the tester to construct a RootApproximator.
    * @param val the value of the number to be squared and guessed.
    * @param eps the gap in which the approximation is considered acceptable.
     public RootApproximator(double val, double eps)
          value = val;
          square = Math.sqrt(val);
          epsilon = eps;
   /** Uses the algorithm where 1 is the first initial guess of the
    *  square root of the inputted value. The algorithm is defined by
    *  "If X is a guess for a square root of a number, then the average
    *  of X and value/X is a closer approximation.
    *  @return increasingly closer guesses as the method is continually used.
   public double nextGuess()
         final int TRIES = 10000;
         double guess = 1;
          for (double i = 1; i < TRIES; i++)
               double temp = value / guess;
               guess = (guess + temp) / 2.0;
          return guess;
   /** Determines if there are more guesses left if the difference
    *  of the square and current guess are not equal to or less than
    *  epsilon.
    *  @return the value of the condition.
   public boolean hasMoreGuesses()
          return (square - guess <= epsilon);
   private double square;
   private double value;
   private double epsilon;
   private double guess;
here is the tester:
public class RootApproximatorTester
   public static void main(String[] args)
      double a = 100;
      double epsilon = 1;
      RootApproximator approx = new RootApproximator(a, epsilon);
      System.out.println(approx.nextGuess());
      System.out.println("Expected: 1");
      System.out.println(approx.nextGuess());
      System.out.println("Expected: 50.5");
      while (approx.hasMoreGuesses())
         approx.nextGuess();
      System.out.println(Math.abs(approx.nextGuess() - 10) < epsilon);
      System.out.println("Expected: true");
and here is the output:
10.0
Expected: 1 // not sure why this should be 1, perhaps because it is the first guess.
10.0
Expected: 50.5 // (100 + 1) / 2, average of the inputted value and the first guess.
true
Expected: true
i'm new to java this is my first java course and this stuff is frustrating. i'm really clueless as to what to do next, if anyone could please give me some helpful advice i would really appreciate it. thank you all.

i'm new to java this is my first java course and this
stuff is frustrating. i'm really clueless as to what
to do nextMaybe it's because you don't have a strategy for what the program is supposed to do? To me it looks like a numerical scheme for finding the squareroot of a number.
Say the number you want to squarerroot is called value and that you have an approximation called guess. How do you determine whether guess is good enought?
Well in hasMoreGuesses you check whether,
(abs(value-guess*guess) < epsilon)
The above decides if guess is within epsilon of being the squareroot of value.
When you calculate the next guess in nextGuess why do you loop so many times? Aren't you supposed to make just one new guess like,
guess = (guess + value/guess)/2.0
The above generates a new guess based on the fact that guess and value/guess must be on each side of value so that the average of them must be closer too value.
Now you can put the two together to a complete algoritm like,
while (hasMoreGuesses()) {
   nextGuess();
}In each iteration of the loop a new "guess" of the squareroot is generated and this continues until the guess is a sufficiently close approximation of the squareroot.

Similar Messages

  • Square root approximations and loops, output not as expected

    Hi guys,
    I'm trying to create a program that uses loops to guess the approximate value of a square root of an inputted value within an epsilon value. The program will guess with a value x, then use (x + (value/x))/2 to guess a closer value, where value = sqrt(input).
    Here is my solution class:
    public class RootApproximator
       public RootApproximator(double val, double eps)
              value = val;
              square = Math.sqrt(val);
              epsilon = eps;
              lower = square - epsilon;
       public double nextGuess()
              for (double i = 1; i < lower; i++)
                   i = (i + (value/i)) / 2;
                   guess = i;
              return guess;
       public boolean hasMoreGuesses()
              return (square - guess <= epsilon);
       private double square;
       private double value;
       private double epsilon;
       private double guess;
       private double lower;
    And here is my tester:
    public class RootApproximatorTester
       public static void main(String[] args)
          double a = 100;
          double epsilon = 1;
          RootApproximator approx = new RootApproximator(a, epsilon);
          System.out.println(approx.nextGuess());
          System.out.println("Expected: 1");
          System.out.println(approx.nextGuess());
          System.out.println("Expected: 50.5");
          while (approx.hasMoreGuesses())
             approx.nextGuess();
          System.out.println(Math.abs(approx.nextGuess() - 10) < epsilon);
          System.out.println("Expected: true");
    }Something is wrong with my loop, because the expected values are not appearing. Here is what the output looks like:
    50.5
    Expected: 1
    50.5
    Expected: 1
    ... // there should be more here, it should print:
    // true
    // Expected: true
    If anyone could please point out my errors so I can finish this program I would certainly appreciate it. Thank you all.

    I've modified your code a bit.
    class RootApproximator
         private double value;
         private double accuracy;
         private double firstGuess;
         public RootApproximator(double val)
              value = val;
              accuracy = 1;
         public double makeGuess()
              double guess = firstGuess;
              for (double i = 1; i <= accuracy; i++)
                   double temp = value / guess;
                   guess = (guess + temp) / 2.0;
                   System.out.println("Next Guess: "+guess);
              return guess;
         public void setFirstGuess(double num)
              firstGuess = num;
         //the higher the accuracy, the closer the square root will be
         public void setAccuracy(int num)
              accuracy = num;
    public class Test
         public static void main(String[] args)
              System.out.println("Number to take square root of:");
              java.util.Scanner input = new java.util.Scanner(System.in);
              double num = input.nextDouble();
              System.out.println("Number of times to iterate:");
              int acc = input.nextInt();
              System.out.println("First Guess:");
              double guess = input.nextDouble();
              RootApproximator approx = new RootApproximator(num);
              approx.setAccuracy(acc);
              approx.setFirstGuess(guess);
              double sqrt = approx.makeGuess();
              System.out.println("--------------------");
              System.out.println("Final Guess: "+sqrt);
              System.out.println("Actual Square Root: "+Math.sqrt(num));
    }

  • Help with square root calculator

    Hi: I am new to Java. Trying to write code for square root calculator of numbers 1-10. Have no idea where to start.

    Using pencil and paper, manually extract the square root of a number, and write down the steps that you use to do that. Create a Java program that does those steps.
    A Java Tutorial is here: http://java.sun.com/docs/books/tutorial/

  • How to edit 1440 x 1080 with SQUARE PIXELS?

    Yes, I know it's weird. I would like to edit 1440 x 1080 with square pixels - HD with a standard aspect ratio. Unfortunately, any preset in 1440 x 1080 (HDV for example) is anamorphic and won't let me change it to square pixels. How do I create a project in 1440 x 1080 with square pixels?
    I know I can alter the aspect ratio on export, but that would squish the images, so that won't do. I need to maintain square pixels from start to finish.

    Ah, but it is not coming from a camera. I am creating it from images. In fact the main purpose of creating this video is
    so the projectionist can adjust zoom and focus to bring the projector back to optimal "standard" settings while the audience has something funny to watch. Sure, I could create it in DV 4:3 format, but my images are already sized for 1080 height (I made a similar video for adjusting the zoom/focus for widescreen, which is really 4:3 with the top and bottom offscreen since the projector doesn't do 16:9). It is an older projector before HD standards and 16:9, but is higher resolution than the typical 4:3 formats. Another reason I want to use higher resolution is because I previously made the video at 720 x 480 resolution and it looks much better in HD.
    So the question remains - how do I set custom resolution with square pixels?

  • Square Root Help

    ok, I used the search function and had a hard time understanding how to do things and I don't think any of the posts answered my question.
    Right now, I am working on an assignment that makes me figure out the quadratic formula. I am having trouble with the square root part of the program.
    For instance that part is: sqrt( b*b - 4*a*c)
    I want my program to be able to tell if the square root is a perfect square then go ahead an calculate it, but if it is not, then we just want to reduce the square root function, or even if it is a perfect square, I need to make the program reduce fractions when possible.
    For instance, here is an example that is a perfect square: sqrt(25) = 5 , the program would just spit out five automatically.
    BUT
    If it were: sqrt(24), then I would want it to reduce it to 2 sqrt(6) and that is what the program would pop out.
    Also, I am having trouble on how to tell the program how to "reduce fractions" , because if I had the square root in the last example, I might be able to reduce fractions for the whole quadratic function.
    example. ( 2 - 2 sqrt(6) ) / 2              would reduce to   1 - sqrt(6) and that is what the program would say.
    basically it seems like we are avoiding actually dealing with decimals.
    If you could just point me in the right direction or have a good link, it would be appreciated!!!

    It seems to me your real problem is taking a number and finding all prime factors of that number. Once you have a list of those, you know you can pull duplicates out of the square root. If all of them were duplicates, you had a perfect square.
    Here's a simple program I scrawled out to factor and reassemble into the appropriate form:
    import java.util.*;
    class FactorTest {
        public static void main(String[] args) {
            int value = 96;
            LinkedList<Integer> factors = new LinkedList<Integer>();
            LinkedList<Integer> primeNumbers = new LinkedList<Integer>();
            populatePrimeList(primeNumbers);
            while (value > 1) {
               boolean factorFound = false;
               for (int prime : primeNumbers) {
                  if (value % prime == 0) {
                     value = value / prime;
                     factors.add(prime);
                     factorFound = true;
                     break;
               if (!factorFound) {
                  expandPrimeList(primeNumbers);
            int left = 1;
            int right = 1;
            int lastValue = 1;
            for (int factor : factors) {
               if (lastValue == factor) {
                  left *= factor;
                  lastValue = 1;
               else {
                  right *= lastValue;
                  lastValue = factor;
            right *= lastValue;
            System.out.println(left + " sqrt " + right);
        public static void populatePrimeList(LinkedList<Integer> primes) {
           primes.add(2);
           primes.add(3);
           primes.add(5);
           primes.add(7);
           primes.add(11);
           primes.add(13);
        public static void expandPrimeList(LinkedList<Integer> primes) {
           int testPrime = primes.get(primes.size() - 1);
           boolean foundFactors;
           do {
              foundFactors = false;
              testPrime += 2;
              for (int prime : primes) {
                 if (testPrime % prime == 0) {
                    foundFactors = true;
                    break;
           } while (foundFactors);
           primes.add(testPrime);
    }Edited by: jboeing on Jan 15, 2008 11:18 AM

  • Problem with java swing button and loop

    Problem with java swing button and loop
    I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
    I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
    When I click on start button it must do next:
    Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
    And when I click on stop button it must do next:
    Start button must set enabled and selected and Stop button must set disenabled.
    Field status is set to 0.
    This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
    There is java code, so you can get better picture:
    /** start button */
    public void gStart_ActionEvents() {
    try {
    ivjGStart.setEnabled(false);
    ivjGStop.setEnabled(true);
    ivjGStop.setSelected(true);
    getJTextPane1().setText("Program is running ...");
    Status = 1;
    } catch (Exception e) {}
    /** stop button */
    public void gStop_ActionEvents() {
    try {
    ivjGStart.setEnabled(true);
    ivjGStart.setSelected(true);
    ivjGStop.setEnabled(false);
    getJTextPane1().setText("Program is NOT running ...");
    Status = 0;
    } catch (Exception e) {
    /** procedure IzvajajNeprekinjeno() */
    public void IzvajajNeprekinjeno() {  //RunLoop
    try {
    int zamik = 2000; //delay
    do {
    Thread.sleep(zamik);
    PreberiDat(); //procedure
    } while (Status == 1);
    } catch (Exception e) {
    So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
    Any help will be appreciated.
    Best regards,
    Tomi

    This is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
    Since java is task-based this will happen if you do like this:
    1. Button "Start" is pressed. Thread running: GUI_Thread
    2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
    3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
    4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
    5. Call PreberiDat(). Thread running: GUI_Thread
    6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
    Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
    What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    This tutorial explains how to build a multi threaded gui.
    /Lime

  • Downloaded yosemite and my iPhotos pics now appear as a grey square and triangle with an ! in it with in the new photos program

    I have a mac book pro and i just downloaded yosemite. after i downloaded yosemite i went to the new photos program as he iPhoto icon was no longer there and i followed the instructions. i then opened my pics and they all seemed to be there but when i enlarge them or double click on them all i see is a grey screen with a grey square with a grey triangle with an exclamation point in it. so in reality the pics aren't really there! maybe they are somewhere else but i do not know.
    just so you know: before i downloaded yosemite i did all the upgrades my computer said i needed to do, no iPhoto upgrade was listed. i didn't do any specific backup before downloaded yosemite but i do have a time machine connected to the computer so i do believe that i therefore have a backup. i am not exactly sure what version iPhoto i had but perhaps my iPhoto and the new photos program are not compatible. i say that because when i went into applications and clicked on iPhoto (as it was listed there) it said "in order to open "iPhoto" you need to update to the latest version. the version of iPhoto installed on this mac is not compatible with os x yosemite. download the latest version for free from the mac app store." so i searched the app store and it says that version is not available. the app store does list iPhoto in my purchased products but it only says update and not download. i clicked on update it doesn't appear to do anything but do a spinning circle for a few seconds and then nothing further. i don't know what to do next! what happened and how do i go about fixing this problem?

    The exclamation mark means that the app has lost the link to the actual file.
    First step: try and make sure the iPhoto Library is working correctly:
    Go to the App Store and check out the Purchases List. If iPhoto is there then it will be v9.6.1
    If it is there, then drag your existing iPhoto app (not the library, just the app) to the trash
    Install the App from the App Store.
    Sometimes iPhoto is not visible on the Purchases List. it may be hidden. See this article for details on how to unhide it.
    http://support.apple.com/kb/HT4928
    One question often asked: Will I lose my Photos if I reinstall?
    iPhoto the application and the iPhoto Library are two different parts of the iPhoto programme. So, reinstalling the app should not affect the Library. BUT you should always have a back up before doing this kind of work. Always.

  • Downloaded yosemite and my iPhotos pics now appear as a grey square and triangle with an ! in it in the new photos program

    I have a mac book pro and i just downloaded yosemite. after i downloaded yosemite i went to the new photos program as he iPhoto icon was no longer there and i followed the instructions. i then opened my pics and they all seemed to be there but when i enlarge them or double click on them all i see is a grey screen with a grey square with a grey triangle with an exclamation point in it. so in reality the pics aren't really there! maybe they are somewhere else but i do not know.
    just so you know: before i downloaded yosemite i did all the upgrades my computer said i needed to do, no iPhoto upgrade was listed. i didn't do any specific backup before downloaded yosemite but i do have a time machine connected to the computer so i do believe that i therefore have a backup. i am not exactly sure what version iPhoto i had but perhaps my iPhoto and the new photos program are not compatible. i say that because when i went into applications and clicked on iPhoto (as it was listed there) it said "in order to open "iPhoto" you need to update to the latest version. the version of iPhoto installed on this mac is not compatible with os x yosemite. download the latest version for free from the mac app store." so i searched the app store and it says that version is not available. the app store does list iPhoto in my purchased products but it only says update and not download. i clicked on update it doesn't appear to do anything but do a spinning circle for a few seconds and then nothing further. i don't know what to do next! what happened and how do i go about fixing this problem?

    The exclamation mark means that the app has lost the link to the actual file.
    First step: try and make sure the iPhoto Library is working correctly:
    Go to the App Store and check out the Purchases List. If iPhoto is there then it will be v9.6.1
    If it is there, then drag your existing iPhoto app (not the library, just the app) to the trash
    Install the App from the App Store.
    Sometimes iPhoto is not visible on the Purchases List. it may be hidden. See this article for details on how to unhide it.
    http://support.apple.com/kb/HT4928
    One question often asked: Will I lose my Photos if I reinstall?
    iPhoto the application and the iPhoto Library are two different parts of the iPhoto programme. So, reinstalling the app should not affect the Library. BUT you should always have a back up before doing this kind of work. Always.

  • Has anybody had the following error while trying to download iTunes 10.5? There is a problem with Windows Installer package. A program required for this install to complete could not be run.

    Has anybody had the following error while trying to download iTunes 10.5? There is a problem with Windows Installer package. A program required for this install to complete could not be run.

    Go to "control panel" then "add or remove programs".  Highlight "Apple software update"  Choose "change" click "Repair"  This should do the trick.  Then download and install iTunes 10.5 again.

  • Tried to install iTunes 10.5 this morning but an error appeared saying "problem with windows installer package. A program required for this install to complete could not be run." Can someone please help

    I tried to install iTunes 10.5 this morning but an error appeared saying "problem with windows installer package. A program required for this install to complete could not be run." Can someone please help

    Firstly, are you installing iTunes for the first time or are you updating your current version of iTunes?
    If you're installing iTunes for the first time have you tried redownloading the installer package? Perhaps the file you downloaded originally is corrupted...
    http://www.apple.com/itunes/
    If you've tried that, then try installing iTunes as your computer's administrator. To do this right-click the install package and choose "Run as administrator".
    If you're updating iTunes to the most recent version try repairing the Apple Software Update program on your computer. It's under the add/remove programs.
    1. Open the control panel
    2. Open Add/Remove programs (called "Programs and Features" in Windows 7)
    3. Navigate to "Apple Software Update" in the list and click on it
    4. Click on "Change" then select "Repair" (or just select the repair option in Windows 7)
    Once you repair this, try running iTunes and the update again.
    Fingers crossed!

  • I keep getting an error message that reads: There is a problems with this windows installer package A program required for this install to complete could not be run. Contact your support personnel or package vendor. How do I correct this problem.

    I keep getting an error message that reads: There is a problems with this windows installer package A program required for this install to complete could not be run. Contact your support personnel or package vendor. How do I correct this problem. HELP !!!!!!!!!!!!!!

    Try the following user tip:
    "There is a problem with this Windows Installer package ..." error messages when installing iTunes for Windows

  • Trying to down load Itunes but I get a message : There is a problem with this Windows Installer package a program run as part of the setup did not finish as expected. Contact your support personnel or package vendor.

    When downloading Itunes I get this message:
    There is a problem with this Windows Installer package a Program run as part of the setup did not finish as expected.
    Contact your support personnel or package vendor..
    is there a number for me to call or can someone explain what has happen...
    Thank you for your help....

    Try the following user tip:
    "There is a problem with this Windows Installer package ..." error messages when installing iTunes for Windows

  • I went to update my itunes and I get the following message:  there is a problem with this windows installer package, a program required for this install to complete could not be run.  I uninstalled the old itune and reinstalled the new one and i get the s

    I went to upgrade itunes and when it finally downloaded, i got the following message:  There is a problem with this windows installer. A program required for this install to complete could not be run.
    I was advised to unistall the old itune, which i did and then loaded the latest itune 10.5 i think.  It dowloaded fine to a point and before finishing, it came up with the same message.
    Is the problem with the itune installer or my windows installer on my laptop?

    Repair your Apple software update.
    Go to START/ALL PROGRAMS/Apple Software Update. If it offers you a newer version of Apple Software Update, do it but Deselect any other software offered at the same time. Once done, try another iTunes install
    If you don't find ASU, go to Control Panel:
    START/CONTROL PANEL/Programs n Features/highlight ASU and click REPAIR,

  • Downloaded the latest itunes and when i go to install it i get a message saying there is a problem with this windows installer package a program required for the install to complete could not be run, contact your support personnal or package vendor

    When `ve downloaded the latest itunes and then i go to install it i get a message saying there is a problem with this windows installer package a program required for the install to complete could not be run, contact your support personnal or package vendor any ideas anyone ? thanks

    Try the following user tip:
    "There is a problem with this Windows Installer package ..." error messages when installing iTunes for Windows

  • HT1349 Hi all,I have just purchased new iphone but have difficulty in completing the itunes download with message : problem with Windows installer package. A program run as part of the setup did not finish as expected.

    Hi all,I have just purchased new iphone but have difficulty in completing the itunes download with message : problem with Windows installer package. A program run as part of the setup did not finish as expected.
    Would appreciate help...its driving me up the wall!!

    Perhaps let's first try updating your Apple Software Update.
    Launch Apple Software Update ("Start > All Programs > Apple Software Update"). Does it launch and offer you a newer version of Apple Software Update? If so, choose to install just that update to Apple Software Update. (Deselect any other software offered at the same time.)
    If the ASU update goes through okay, try another iTunes install. Does it go through without the errors this time?

Maybe you are looking for

  • TS4020 Is there a way to copy or transfer contacts from one icloud account to another?

    My wife and I just upgraded from the 4S to the 5C, but apparently we were using the same icloud account, and now we need to separate them so that we can make changes and not have it affect the other phone.

  • S20 Memory upgrade

    Hi, I have the following: Lenovo ThinkStation S20 Xeon W3550 Quad-Core Processor (3.06GHz 1066MHz 8MB) 4gb (2 x 2gb) udimm ddr3 1333MHz, 300GB SAS (15k) with SAS Controller Card NVIDIA Quadro 2000 I would like to add more memory, and would like to kn

  • Error while trying to sync audio and video.

    Suddenly out of the blue I'm have all sorts of problems with Logic 8. I keep getting the "error while trying to synchronize audio and midi" error message. Even when I'm just using using the audio side. Do you know of a local logic tech that could che

  • Wireless does not hold connection with b43 driver!

    Hi everybody!! It's my first time here in the forum, so nice to meet you. I have a laptop Acer Aspire 3050 and I recently formatted it to install the new Arch 2009.08. It's pretty cool, but I can't make my wireless card (Broadcom BCM4318) work with b

  • In Solution Landscape Application Servers are not displaying

    Dear All, We are integrated SOLMAN (7.0 Ehp1) server with R/3 Dev,Qua,Prd servers but in DSWP >Operations>Solution Monitoring-->System monitoring / Administration .We can see the Dev,Qua,Prd servers but our requirement is under Dev server we have 4 a