To calculate square root of a number.
coffee> srr = (x,est) -> if Math.abs(est*est - x) < 0.0005 then est else srr x, (est + x/est)*0.5
[Function]
coffee> srr 2,1
1.4142156862745097
Easy translation from English to code.
If the square of a given estimate is within the tolerance of 0.0005 from the number, then the given estimate is the result, otherwise the result is the one given by the function with a new estimate which is the average of the given estimate and the quotient of the number divided by the given estimate.
Fairly declarative reading. If we do minimum necessary operational reasoning we can have an iterative formulation instead of the above recursive formulation.
If the square of a given estimate is within the tolerance of 0.0005 from the number, then the given estimate is the result, otherwise update the estimate by a new estimate which is the average of the given estimate and the quotient of the number divided by the given estimate and repeat the process until the tolerance is achieved.
Or equivalently, we can say while tolerance is not achieved, update the estimate.
Code in sri.coffee file indented as required by coffeescript
sri = (x,est) -> while Math.abs(est*est - x) > 0.0005
est = (est + x/est)*0.5
console.log(sri 2,1)
Let us execute this.
$ coffee sri.coffee
[ 1.5, 1.4166666666666665, 1.4142156862745097 ]
It is the peculiarity of while loop of coffeescript the result returned is an array of all estimates.
No comments:
Post a Comment