Implement the heron method to locate the square root

Assignment Help Data Structure & Algorithms
Reference no: EM13944238

The Heron Method for approximating the square root of a number states that if x is a guess for the square root of n then a better guess x' is:

x' = [x + (n/x)] / 2

Naturally this process can be repeated using x' in place of x the next time through the loop. The loop can stop when the difference between the previous and next guesses is small enough.

A programmer wrote the following code to implement the Heron Method to locate the square root of any number:

2374_ff.png

function heronSqrt(n)
{
var DELTA = 1.0E-10;
var nextGuess;
var prevGuess = n;
do
{
nextGuess = (prevGuess + (n/prevGuess))/2.0;
prevGuess = nextGuess;
} while (nextGuess-prevGuess > DELTA)
return nextGuess;
}

However, the code does not work properly. Fix the program so that it works. Also list a set of test cases that will thoroughly exercise the Heron Method List a set of test cases that will thoroughly exercise the Heron Method code above. Consider all possible kinds of square roots.

The following are some guidelines for choosing test cases:

• Have several test cases where the code is expected to work correctly on fairly standard input. These are positive tests and correspond to test cases 1 and 3 above.

• Have several test cases where the code is expected to work correctly on boundary input (input that is close to being "wrong"). These are positive boundary tests and correspond to test cases 9, 10, and 11.

  • Have as many "special case" positive test cases as necessary, where the input is correct but requires accounting for special cases. These could be either positive or negative test cases, but in this example corresponds to test cases 4, 5, 7, 8, and 10.

Selecting test cases

Determining which inputs to use to create good test cases requires careful thought. Consider the following code for a RootFinder object that finds the integer root of a number. The algorithm is a binary search using a reversible function:

function RootFinder(number, root)
{
    this.number = number;
    this.root = root;
}
 
RootFinder.prototype.approxEqual = function(x, y)
{
    var EPSILON = 1E-12;
    return Math.abs(x - y) <= EPSILON;
}
    
RootFinder.prototype.pow = function(number, power)
{
    var result = 1;
    for (var i=0; i<power; ++i)
    {
        result *= number;
    }
    return result;
}
    
RootFinder.prototype.getRoot = function()
 {
    // binary search for resultvar left = 0;
    var right = this.number;
    var mid;
        
    do
    {
        mid = (left + right)/2.0;
        if (this.pow(mid, this.root) < this.number)
            left = mid;
        else
            right = mid;
    } while (!this.approxEqual(left, right));
    return mid;
}

(The source code is available for both RootFinder.js and RootFinder.html)

Consider test cases for this code; the only possible inputs are the number and the root desired. What inputs are valid? What inputs are invalid? What valid inputs will produce a good result in this version? What valid inputs will produce bad results? Clearly, some knowledge of the problem domain is required. The table below classifies some inputs:

Case

number

root

Valid?

Expected

Notes

1

25.0

2

Yes

5.00

Should work

2

-25.0

2

No

none

No even roots of negatives

3

27.0

3

Yes

3.00

Should work

4

-27.0

3

Yes

-3.00

Should work

5

0.25

2

Yes

0.500

Should work

6

-0.25

2

No

none

No even roots of negatives

7

0.125

3

Yes

0.500

Should work

8

-0.125

3

Yes

-0.500

Should work

9

1.00

2

Yes

1.00

Should work

10

-1.00

3

Yes

-1.00

Should work

11

0.0

2

Yes

0.00

Should work

Of these test cases, the presented code only passes cases test cases 1, 3, 9, and 11! The remaining test cases ended up in an infinite loop. The code presented above was written to work on all the "normal" cases; however, the assumptions were wrong for ranges of numbers in which the other test cases fell. For instance, the code assumes that all roots of a number will be found between 0 and the number itself. However, this assumption is false in test cases 5, 7, and 8. Cases 2 and 6 expose the lack of precondition checking. Finally, cases 4, 8, and 10 have left and right reversed.

Evaluating Test Cases

How does a programmer know when the output of a method is correct? Evaluating the correctness of test cases is another difficult issue. In the case of the RootFinder above, the algorithm's results can be predicted with known input, which is the way a majority of test cases are structured. For instance, if the expected answer is 10.0, then inputs of (1000.0, 3) or (100.0, 2) should yield 10.0 as the answer. Another powerful method is to use an oracle. An oracle is another method that is known to produce the correct result, and in the RootFinder example, that method is Math.pow(). The same inputs to Math.pow() can be provided to the constructor of RootFinder, and the results can be compared. One may ask why someone would wish to write a new method that does the same thing as an existing oracle. The answer is that the new method may be designed to work faster than the oracle or that an entire system is being re-written, yet the outputs of the systems should match.

• Have several test cases where the code is expected to check preconditions for bad input. These are negative test cases and correspond to test cases 2 and 6.

Reference no: EM13944238

Questions Cloud

What is martin luther king jr in-group : What is Martin Luther King Jr in-group and what are the unifying values or the ascribed status that provides its solidarity?
Discuss one of main arguments for the existence of god : Theism offers a clear way to approach the relationship between faith and reason. This can be seen by considering some of the arguments for the existence of God by theists such as Saint Thomas Aquinas. Explain the idea of theism.
Portfolio and a reflective log for business : Read the assignment carefully and produce a portfolio and a reflective log for business. Attached is the assignment as well as a handbook to guide you in the process.
Prepare a statement of financial position for the business : Drawings for the year to 30 September 2010 15,000 Using this information, prepare a statement of financial position for the business using the standard layout illustrated in Example 2.5 on p.48 of Atrill, P., & E. McLaney, (2011) Accounting and Fi..
Implement the heron method to locate the square root : The Heron Method for approximating the square root of a number states that if x is a guess for the square root of n then a better guess x' is:
What is type 1 hypersensitivity mediated by : What is type 1 hypersensitivity mediated by? give example of this type of hypersensitivity.
Consumer decision-making process : As a recently appointed executive of a leading marketing consultancy, you are required to prepare an essay for your director on the consumer decision-making process.
Simple linear regression equation analysis : 1. Below is the output from a simple linear regression equation analysis of this year's NCAA men's basketball tournament (last March).  It is an attempt to predict the score that the winning team has based on the number of victories that it had pr..
What objections can be raised against their validity : Several arguments have been proposed to show that the belief in God is not an unreasonable option. Outline the two major arguments-cosmological and teleological-identifying their premises and their conclusions. Are these arguments convincing? What..

Reviews

Write a Review

Data Structure & Algorithms Questions & Answers

  Design a dynamic programming algorithm to find the value

Design a dynamic programming algorithm to find the value of the optimal plan. Implement your algorithm using any programming language you prefer. Describe the recurrence relation used by your algorithm at the top of your program or in a separate f..

  Question about software importance

Determine what makes software so important and list a number of ways that software has an impact on our life.

  True or false about networking

2- A print queue must be set up for every printer on the network served by a print server. True False

  Determine algorithm for cs curriculum consists of n courses

Determine an algorithm which works directly with this graph representation, and calculates minimum number of semesters necessary to complete the curriculum.

  How does the algorithm you chose affect the result

How do the algorithm techniques of fragmentation affect the end result of sorting through larger amounts?

  Question about communication recovery plan

Think about a natural or man made disaster, and explain how a communications network could be recovered from such a disaster.

  Initalize the element with appropriate integer values

delcare and array of integer of size 10 and initalize the element with appropriate integer values

  Creating a random file of the signs

Create a random file of the signs of all angles from zero degrees to ninety degrees. Make every entry accurate to three places. Write a program that will show the sign of any angle typed on the keyboard.

  Writing a java program

The history teacher at your school requires help grading a True or False test. The students' IDs and test answers are stored in a file document.

  Algorithm to find maximum sum of contiguous sublist

Using dynamic programming, write an algorithm to find the maximum sum of contiguous sublist of a given list of n real values.

  Show result of inserting keys using linear probing

Show the result of inserting these keys using linear probing, using quadratic probing with c1 = 1 and c2 = 3, and using double hashing with h2(k) = 1 + (k mod (m ¡ 1)).

  Describe a polynomial time algorithm

Describe a polynomial time algorithm that solves the following decision problem: Given a graph G and an edge f in it, does G have a cycle containing f?

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd