Standing on the shoulders of giants. RSS 2.0
# Wednesday, January 04, 2006

See also: A horrible way to calculate a squareroot

using System;
using System.Query;

namespace SquareRoot
{
class Program
{
static void Main(string[] args)
{
int input = 16;
decimal margin = 0.01M;

Func<decimal, decimal> abs = (decimal x) =>
x < 0 ? -x : x;

Func<decimal, bool> goodEnough = (decimal guess) =>
abs(guess * guess - input) < margin;

Func<decimal, decimal> newGuess = (decimal guess) =>
(guess + input / guess) / 2;

Console.WriteLine( "Guess {0}", Try(1, goodEnough, newGuess) );
Console.ReadLine();
}

static decimal Try(decimal guess, Func<decimal, bool> goodEnough, Func<decimal, decimal> newGuess)
{
if (!goodEnough(guess))
{
return Try(newGuess(guess), goodEnough, newGuess);
}

return guess;
}
}
}

Wednesday, January 04, 2006 2:32:56 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] - Trackback
Development
Comments are closed.
About
© Copyright 2009
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.8275.16006
All Content © 2009, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)