Computing The Square Root Of X

[Solved] Computing The Square Root Of X | Swift - Code Explorer | yomemimo.com
Question : Computing the Square Root of x#

Answered by : sumit-rawal-ig4gaypbyn28

{"tags":[{"tag":"p","content":"To compute the square root of a number, x, we first need to make an initial estimate, y, let\u2019s say 1. We improve the estimate by taking the average of y and x\/y.\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"Let\u2019s look at an example. The table below shows how Newtons method would compute the square root of 4 by approximation.\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"svg viewer\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"If we continue the above calculations, the average would eventually converge to 2.\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"Brace yourself because below, you\u2019ll be introduced to your first extensive Scala program!\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"Implementation in Scala\n "},{"tag":"p","content":"To implement the above method in Scala, we need to define five functions interdependent with each other.\n "},{"tag":"p","content":"\n "},{"tag":"p","content":"abs(): will return the absolute value of a given number\n "},{"tag":"p","content":"isGoodEnough(): will let us know if the average is close enough to the actual value\n "},{"tag":"p","content":"improve(): will return the average of y and x\/y\n "},{"tag":"p","content":"sqrtIter(): a recursive function which will compute each iteration of Newton\u2019s method\n "},{"tag":"p","content":"sqrt(): Will use the sqrtIter() function and return the square root of the given number\n "},{"tag":"p","content":"When defining a function dependent on other functions, make sure to define them above the dependent function.&nbsp;"},{"tag":"textarea","content":"def abs(x: Double) =\n if (x < 0) -x else x\n\ndef isGoodEnough(guess: Double, x: Double) =\n abs(guess * guess - x) \/ x < 0.0001\n\ndef improve(guess: Double, x: Double) =\n (guess + x \/ guess) \/ 2\n\ndef sqrtIter(guess: Double, x: Double): Double =\n if (isGoodEnough(guess, x)) guess\n else sqrtIter(improve(guess, x), x)\n\ndef sqrt(x: Double) = sqrtIter(1.0, x)","code_language":"scala"}]}

Source : | Last Update : Tue, 30 May 23

Answers related to computing the square root of x

Code Explorer Popular Question For Swift