0

I need to implement Newtons method for finding square roots with given count count signs after floating point in Delphi 7. I wrote this code:

program NewtonMethod

{$APPTYPE CONSOLE}

uses
  SysUtils, Math;

const
  signCount = 50; //Signs after floating point count

var
  number, curRoot, prevRoot: Extended;
  precision: Extended;

function input(): Extended;
begin
  Write('x=');
  try
    Readln(number)
  except
    Writeln('Invalid input data, please try again');
    Input();
  end;
end;

begin
  input();
  curRoot := sqrt(number); //Íà÷àëüíàÿ
  precision := 1 / power(10, signCount);
  prevRoot := 0;

  repeat
    prevRoot := curRoot;
    curRoot := prevRoot - (Power(prevRoot, 2) - number) / (2 * prevRoot);
  until
    Abs(curRoot - prevRoot) < precision;

  Writeln(curRoot);
  ReadLn;
end.

Please, answer to my questions:

  • Is this code correct ?
  • How to print result root in normal (not exponential) form with all signs ?
  • Input values may be very large (up to 200 signs). Can this code work with them ?

And suggest me, how can I improve my code ?

TLama
  • 75,147
  • 17
  • 214
  • 392
skeeph
  • 462
  • 2
  • 6
  • 18
  • What does "up to 200 signs" mean - up to 200 digits, decimal? If so you will need to use a [BigDecimal class](http://stackoverflow.com/questions/9690133/bcd-math-library-for-arbitrary-big-numbers). Get it working for small numbers first, then change to use a big decimal library. Also Matt's note below about you directly calculating the square root using sqrt() is correct - you shouldn't do that since it gives you the answer already! – David Dec 28 '14 at 17:43

1 Answers1

1

curRoot:=sqrt(number); << looks like you're working out the square root of a number directly here, not using a method.

You should choose a "first guess" using some other method... If this is just for fun, try half the number

You might find this page useful: https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number

The Extended datatype can only do around 20 decimal places. 200 decimal places is a tough call and would probably be pretty difficult to do

Matthew Sainsbury
  • 1,470
  • 3
  • 18
  • 42