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));
}

Similar Messages

  • 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.

  • K7n2g ILSR and SPDIF output not working

    just got a new k7n2g ILSR mobo and cant get the coaxial spdif output to work.
    Have attached the s bracket connector and a coaxial cable from that to my videologic digitheatre. My speakers don't seem to be receiving any signal however. Checked the audio settings on the nforce control panel and all seems sweet. any suggestions?
    Thanks for any replies

    I have the very same problem. I thought that the S-Bracket was defected so I borrowed one from a friend of mine. We have the very same board and we bought it the very same day. And it did not work either. :(
    Then I made a little test. The user's manual displays the pin layout of the S-Bracket connector on the mobo so I connected two little wires to the appropriate connectors and connected the wires to a standard RCA connector. Then I connected this to my receiver's coax port and it worked!
    So it seems to me that the S-Bbracket was (and IS) defected. Then I thought that my friend and I had the same faulty series of S-Bracket but now I don't know what to think...

  • Both left speaker and headphone output not working

    I noticed a week ago that the left headphone audio output wasn't working, and shortly after I realized that my left speaker wasn't working either. I thought maybe it was a matter of updating some software, but everything is up to date. Anyone encouter this problem before?

    Solved my own problem,
    System preferences - sound- output- balance.
    Strange thing is I don't recall adjusting those settings. Hope this is helpful to anyone else who has this issue!

  • Strange export result in FCP 7- audio and video output not in sync anymore

    I have a problem exporting edited videomaterial. After export audio and video they are not in sync anymore. There's a difference of 8 sec when exporting audio and video separatly. Movie is total 61 min long.
    Video and sequence settings are HDV1080i50, 25fps, 48khz, 16 bit, mono.
    What could that be ?

    Well now that I look at all the clips in FCP more closely I see some clips from the same tape are in sync and others are out of sync.  And one section of tape which I captured twice was in sync on one clip and out of sync on the other.  So it can't be the tapes.
    Maybe the sync problem is caused by not coordinating the tape playing and FCP capturing properly every time! So I will try re-capturing the problem sections of tape.

  • End Routine Result Package Output not as expected

    I have written an end routine that is based on a one to one mapping of two DSOs A to B, i calculate the value of two key figures which populate the fields, keyfig1 (a total of the amt_field per order) and keyfig2 (a % of the amt_field of keyfig1) .
    My problems is I seem unable to modify my output result package and keep getting no output  result on both key figures keyfig1 and keyfig 2. However my amt_field has changed instead! I want that to remain unchanged. This is my routine is below:
    data: wa_result_package TYPE tys_TG_1.
    types : begin of itabtype,
                     order         type    /BI0/OI_order_field,
                     tot_amt      type     /BIC/OIamt_field,
               end of itabtype.
               data : itab type standard table of itabtype,
                     wa_itab like line of itab.
    sort RESULT_PACKAGE by order_field   ascending.
    clear wa_itab.
    loop at RESULT_PACKAGE into wa_RESULT_PACKAGE.
               At End of order_field.
                      wa_itab-order    = wa_result_package-order_field.
                      wa_itab-tot_amt = wa_itab-tot_amt +
                      wa_result_package-/BIC/amt_field
                       append wa_itab to itab.
               ENDAT.
        wa_itab-order    = wa_result_package-order_field.
        wa_itab-tot_amt = wa_itab-tot_amt + wa_result_package-/BIC/amt_field
    endloop.
    loop at RESULT_PACKAGE into wa_RESULT_PACKAGE.
             read table itab into wa_itab
                         with key order = wa_result_package-order_field.
             if sy-subrc = 0.
                        wa_result_package-/BIC/keyfig1  = wa_itab-tot_amt.
              endif.
    If wa_result_package-/BIC/keyfig1 <> 0.
               wa_result_package-/BIC/keyfig2 =
               wa_result_package-/BIC/amt_field /
               wa_result_package-/BIC/keyfig1* 100.
    else.  wa_result_package-/BIC/keyfig2 = 0.
    endif.
    modify RESULT_PACKAGE from wa_RESULT_PACKAGE transporting /BIC/keyfig1 /BIC/keyfig2.
    endloop.
    Any help will be most appreciated. Thanks in advance.

    Hi,
    Besides the Endroutine tab there is another tab.
    Update fields even if no rule is assigned.
    Have you checked that? If not you will always get initial, for the fields you are updating.

  • Popup window height and width is not as expected

    Hi I am using this peace of code to create a popup. But this popup is not created with
    the specified height and width. It is created with a default size. Please tell me how to
    rectify the problem?
    data:
        l_api_main            type ref to if_wd_view_controller,
        l_cmp_api             type ref to if_wd_component,
        l_window_manager      type ref to if_wd_window_manager,
        l_popup               type ref to if_wd_window.
      l_api_main = wd_this->wd_get_api( ).
      l_cmp_api = wd_comp_controller->wd_get_api( ).
      data: l_i_question type STRING_TABLE,
            l_wa_question type string.
      l_wa_question =  'Issue no. xxxxxxxxxxx created succcessfully. '.
      append l_wa_question to l_i_question.
      l_window_manager = l_cmp_api->get_window_manager( ).
      l_popup = l_window_manager->create_popup_to_confirm(
                  text                   = l_i_question
                  button_kind            = '1'
                  message_type           = '1'
                 close_button           =
                  window_title           = 'Information'
                  window_width           = '500'
                  window_height          =  '500'
    l_popup->open( ).

    Hi Mainak,
    have a look to Thread:
    Popup Sizing
    As you can see there is not yet a way to set the Popup size.
    You have to find the good combination of fields and length in order to get a nice UI.
    The WDA engine try to set the best size, help it...
    Sergio

  • Distinct and Group By not as expected

    Hi,
    I have this sql....
    SELECT
    dbPatID, dbAddDate, dbStaffLastName, RefTypeWord
    FROM
    EPSReferralKPIs
    WHERE
    (dbAddDate >= '2013-01-01' OR '2013-01-01' = '')
    AND (dbAddDate <= '2013-12-31' OR '2013-12-31' = '')
    AND (dbStaffLastName IN ('Swanepoel','Patient','Pelletti','Ray','Qureshi','Grobler','Hedborg','De Kock','Lima','Check In','Hodgson')
    AND (RefTypeWord IN ('PATIENT','OTHER','DOCTOR','','SIBLING')
    ORDER BY
    dbAddDate
    There may be more than one RefTypeWord for a dbPatId however I only want the
    result set to bring back unique dbPatID's and not more than one row containing a
    different RefTypeWord per row.
    Is that possible?
    thanks,

    Hi,
    Please find the query below.However i am not sure whether this is the one which you are expecting.
    SELECT
    dbPatID, dbAddDate, dbStaffLastName, RefTypeWord
    FROM
    EPSReferralKPIs
    WHERE
    (dbAddDate >= '2013-01-01'
    OR '2013-01-01' =
    AND (dbAddDate <=
    '2013-12-31' OR '2013-12-31'
    = '')
    AND (dbStaffLastName IN
    ('Swanepoel','Patient','Pelletti','Ray','Qureshi','Grobler','Hedborg','De
    Kock','Lima','Check In','Hodgson')
    AND (RefTypeWord IN
    ('PATIENT','OTHER','DOCTOR','','SIBLING')
    GROUP By dbPatID,RefTypeWord
    ORDER BY
    dbAddDate
    This wont work unless you apply some aggregation over other fields not included in GROUP BY
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Calculate Square Root?

    Can I use Simplified field notation to calculate the square root of another field? Not having any success.

    No. You need to use the Custom Script option, with some code like this (assuming the name of the other field is Text1):
    event.value = Math.sqrt(+this.getField("Text1").value);

  • Square root function missing

    Whether you use the Dashboard calculator widget or the Calculator that is built into the Apple OS as an application, there is no button for square root.
    If you are using the Calculator application you can toggle the interface from Basic to Scientific to Programmer. Scientific includes buttons that square a number but no button for square root.
    Why? Or am I missing a hidden keystroke or something?

    Remember Square Root is the same as x^(1/2)
    If you have an x^y button (showing x raised to a power) enter the second number as .5, and you'll have a square root. And if you are really starving, there is Emu:
    http://emu48mac.sourceforge.net/

  • Square root is not working...

    I wrote a simple program to derermine the square root of a number, but its not working: Heres the code:
    class root{
         static public void main(String[] args){
              int square = Math.sqrt[4];
              System.out.println("the square root is " + square);
    }I get this error mesage when running:
    C:\java_apps>javac root.java
    root.java:3: cannot find symbol
    symbol : variable sqrt
    location: class java.lang.Math
    int square = Math.sqrt[4];
    ^ (arrow points to dot after "Math")
    1 error
    Thanks!
    Jake

    Math.sqrt() is a method, so you have to invoke it with parentheses:int square = Math.sqrt(4);
    > root.java:3: cannot find symbol
    symbol : variable sqrt
    location: class java.lang.Math
    int square = Math.sqrt[4];
    ^ (arrow points to dot after "Math")Because of the square bracket the compiler is looking for an array sqrt inthe Math class. It can't find one and so you get the message.
    (Note that the Math static methods tend to return double not int, so you will have to
    deal with that as well.)

  • LabVIEW 6.1 If For Loop count terminal is zero then value going through the loop is not passed on to the output of the loop

    Hello, one of our customers just encountered an execution error in a vi running under LabVIEW 6.1, which doesn't exist under LabVIEW 5.1 or 6.01. I have a simple vi that has two encapsulated For Loops. Two string arrays go in, one goes out of the outer loop. Inside the outer loop the first array is indexed. The string which results from this indexing is compared with all other strings from the second string array in the inner loop. If it matches one of the strings of the second array, it is not outputted, otherwise this string goes through the inner For Loop to the output of the inner loop and from there to the output of the outer loop. The count
    terminal of the outer/inner loop is connected to the Array Size of the first/second string array. If the second array is empty, that means that the element in test from the first arry cannot match anything from the second array, so the element in test is send to the output of the inner loop and from there to the output of the outer loop. This works fine in LabVIEW 5.1 and 6.01, but NOT in LabVIEW 6.1. In LabVIEW 6.1 the inner loop is never executed if the count value is zero (which is correct), but the data line running through the loop is not executed either, which is different to what LabVIEW 5.1 and 6.01 do. There, the input string is sent to the output of the inner loop correctly even if the loop counter is zero. The solution is easy - I just have to connect the output of the outer loop to the data line BEFORE it enters the inner loop. But: I don't know if this is a LabVIEW 6.1 bug or if it is supposed to be a feature, but it brings some incompatibility in programming between the
    different LabVIEW versions.
    Best regards,
    Gabsi

    Hi,
    When a for-loop runs zero times, all outputs are 'undefined' (and should
    be).
    Besides, how would LV know what the output of a not executed routine should
    be?
    It might be handled differently in LV5 and LV6, which is unfortunate. In
    both cases, the result is undefined.
    It's not a bug. It's just something that should be avoided in any LV
    version.
    > The solution is easy - I just have to connect the
    > output of the outer loop to the data line BEFORE it enters the inner
    > loop. But: I don't know if this is a LabVIEW 6.1 bug or if it is
    In some cases this does the trick. But if the data is changed in the inner
    loop, this will effect the results if the N is not zero.
    Technically, I think the output in this construction is also 'undefined'.
    But LV handles this as expected / desired.
    Another solution is to use a shift register. If N is zero, the input is
    directly passed through to the output.
    Regards,
    Wiebe.
    "Gabs" wrote in message
    news:[email protected]...
    > LabVIEW 6.1 If For Loop count terminal is zero then value going
    > through the loop is not passed on to the output of the loop
    >
    > Hello, one of our customers just encountered an execution error in a
    > vi running under LabVIEW 6.1, which doesn't exist under LabVIEW 5.1 or
    > 6.01. I have a simple vi that has two encapsulated For Loops. Two
    > string arrays go in, one goes out of the outer loop. Inside the outer
    > loop the first array is indexed. The string which results from this
    > indexing is compared with all other strings from the second string
    > array in the inner loop. If it matches one of the strings of the
    > second array, it is not outputted, otherwise this string goes through
    > the inner For Loop to the output of the inner loop and from there to
    > the output of the outer loop. The count terminal of the outer/inner
    > loop is connected to the Array Size of the first/second string array.
    > If the second array is empty, that means that the element in test from
    > the first arry cannot match anything from the second array, so the
    > element in test is send to the output of the inner loop and from there
    > to the output of the outer loop. This works fine in LabVIEW 5.1 and
    > 6.01, but NOT in LabVIEW 6.1. In LabVIEW 6.1 the inner loop is never
    > executed if the count value is zero (which is correct), but the data
    > line running through the loop is not executed either, which is
    > different to what LabVIEW 5.1 and 6.01 do. There, the input string is
    > sent to the output of the inner loop correctly even if the loop
    > counter is zero. The solution is easy - I just have to connect the
    > output of the outer loop to the data line BEFORE it enters the inner
    > loop. But: I don't know if this is a LabVIEW 6.1 bug or if it is
    > supposed to be a feature, but it brings some incompatibility in
    > programming between the different LabVIEW versions.
    > Best regards,
    > Gabsi

  • Material num and Plant is not displaying in Output

    hi
    i have written this code to get all inspection types...
    while compiling im getting the correct output...
    it is displaying only inspection types ....
    Material num and Plants are not displaying..
    form PROCESS_DATA .
    CLEAR: WA_FINAL,
           WA_QMAT.
    MOVE IT_FINAL TO I_FINAL.
    REFRESH IT_FINAL.
    LOOP AT I_FINAL assigning <fs_fin>.
    LOOP AT IT_QMAT INTO WA_QMAT where MATNR = <fs_fin>-MATNR.
                                       P_werks = <fs_fin>-werks.
    IF SY-SUBRC EQ 0.
    <fs_fin>-ART = WA_QMAT-ART.
    APPEND <fs_fin>-ART TO it_final.
      CLEAR WA_QMAT.
    CLEAR wa_final.
    ENDIF.
      ENDLOOP.
    ENDLOOP.

    Hi
    ya im getting correct values to <fs_fin>
    now its displaying correct values bt in improper format
    Mat num                  Plant                       insp type
      100001                   1210                         05
      100002                    1320                         01
                                                                     02
                                                                     03
                                                                     05
    bt i want the output as below
    Mat num                  Plant                       insp type
      100001                   1210                         05
                                                                    02
                                                                    03
      100002                    1320                         01

  • Square Root and Powers Assignement

    Hey guys
    Ive just started my first year at university, still feeling like ive been thrown in at the deepend. I have a series of assignments to complete for my programming course, and part of one of them is to work out this following:
    d = (square root of) x2 + y2 + z2
    d,x,y and z are are all vriables that ive sorted out earlier. and x2 means x to the power of 2.
    if anyone could give me some pointers on the best way to do this that would be great
    thanks in advance
    glenn

    pointers:
    use java's Math lib.
    also, usually if x is raised to the power of y, people write x ^ y.
    double d = Math.sqrt(16);
    d is 4

  • Loops and system timestamp not synchronized

    Running Labview 8.6.1 on Windows 2000, loops and system timestamp (Windows clock) seem to use different time bases; one second in a loop is not exactly as long as a second in system time. If i run a simple VI as in picture, with a 1-second loop which just prints the system time, the printed timestamp goes faster by about 1ms every 4-5 seconds. The same happens using a Timed loop or a While with a Wait until next ms multiple.
    Why is that? Can i set a loop to match the system time?
    Attachments:
    1sec.png ‏3 KB

    johnsold wrote:
    In the eastern U. S. interconnected power grid the accumulated time is held to within a small fraction of a second when averaged over days.  Over a year the accumulated error is less than parts in 10^12 or better.  The instantaneous frequency can deviate from the nominal 60 Hz by less than 0.1 Hz.
    The system basically uses an integral controller referenced to a NIST atomic clock to force the steady state error to zero.
    Lynn 
    So is that a very technical way of saying "Ben, you are full of Sh#% !"*
    I have not measured the frquency of my AC service in the last three decades or so. I do remember seeing it faster in the summer and slower in the winter. Has it really changed? Silly me thinking that the wide freq input spec I read on wall-warts was there just to handle this variation of freq.
    And to think it has gotten smarter "without a brain".
    Ben
    * I am just trying to catch up what I seem to have missed. The above is all in good humor. No offense intended or taken.
    Message Edited by Ben on 08-03-2009 12:56 PM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

Maybe you are looking for

  • URGENT: Doubt in vendor replication

    hi,    i got an error i.e 1) <b>user sapuser is blocking organizational unit 50000xxx</b> 2) none of the purchasing org's in org, structure exist(inform system admin) while  iam replicating the vendor through in BBPGETVD pls send details imediatly to

  • LR3, PS CS5, Camera Raw 6.2, oh my! Compatibility issues?

    I am using LR3.2, PS CS5 (12.0.1) and Camera Raw 6.2 on Mac OS (Snow Leopard). When I open an image from Lightroom in Photoshop, filters such as Surface Blur take about 10 minutes (literally) to complete. Wile the filter is running, I checked CPU and

  • I updated Firefox and all my bookmarks are lost; how do I restore them?

    I just updated Firefox to 8.0.1., and all my bookmarks are gone. NONE of the suggested articles dealt with this: How do I restore the bookmarks? And why wasn't I asked during the update if I would like to have the bookmarks imported? Also why wasn't

  • Java to XI

    I have written a small program in Java and I have complied it and created the CLASS file. This java program I am planning to use in the Message Mapping. Now if I want to bring this Java program into XI what are the steps I need to do. Please note, I

  • Hisk Disk I/0 on Big table!!

    Hi, We have one big table in our production database 1 GB+ and most of online search done through application & reports use this table. Hence, large amount of I/O occurs & and response time is slow. To reduce the amount of disk reads i've moved the t