Question
Here is a way to compute the square root of a positive real number say x. We make a wild guess that the square root
Here is a way to compute the square root of a positive real number say x. We make a wild guess that the square root is some number g. Then we check if g2 is close to x. If it is we return g as our answer; if not we refine our guess using the formula
g = (g + x/g)/2.0
where g is the new guess. We keep repeating until we are close enough. Write an OCaml program to implement this idea. Since we are working with floating point numbers we cannot check for equality; we need to check if the numbers are close enough. I have written a function called close
1Unless you are extending the factorial to non-integer values through the Gamma function.
for you as well as a function called square. In OCaml floating point operations need special symbols: you need to put a dot after the operation. Thus you need to write, for example, 2.0+.3.0. All the basic arithmetic operations have dotted versions: +., ., /. and must be used with floating point numbers. You cannot write expressions like 2 + .3.5 or 2.0 + 3.0. We will not test your program on negative inputs so we are not requiring you to deal with the possibility that you may get a negative answer. There are of course built-in functions to compute square roots. We have written the tester program to check if you used this; you will get a zero if you use a built-in function for square roots.
(* Q2 TODO: Write your own tests for the mysqrt function. You should NOT test cases for n < 0. *) let mysqrt_tests = [ (* Your test cases go here. *) ]
(* Q2 TODO: Implement mysqrt. *) let mysqrt (x:float) = raise NotImplemented
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started