develooper Front page | perl.perl6.users | Postings from November 2021

Re: how do I turn a real into and array of Integers?

Thread Previous | Thread Next
From:
Sean McAfee
Date:
November 1, 2021 02:38
Subject:
Re: how do I turn a real into and array of Integers?
Message ID:
CANan03aQ9sC5dytVvb3=Ra-BaxHdruuPpTOq-_m9rCjjWNC3KQ@mail.gmail.com
On Sun, Oct 31, 2021 at 6:51 PM ToddAndMargo via perl6-users <
perl6-users@perl.org> wrote:

> >> How do I get more digits out of sqrt?
>
> On 10/31/21 17:50, Kevin Pye wrote:
>  > You don't.
>  >
>  > sqrt is a function which acts on 64-bit floating point numbers, and
> there's no more meaningful digits available. If you need more precision
> you're on your own.
>
> Dang!  I was hoping ther was some thing like UInt.
>

Fortunately, it's easy.

Wikipedia describes the following recurrence formula for approximating the
square root of 2 from an initial guess a₀:

    aₙ₊₁ = (aₙ / 2 + 1 / aₙ)

So just iterate this sequence until successive terms become close enough
for you, using the unlimited precision FatRat type, for example:

    (2.FatRat, { $_ / 2 + 1 / $_ } ... (* - *).abs < 1e-100).tail

This gives the root to a precision of one in a googol.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About