Module for Continued Fractions for approximations started.

This commit is contained in:
Stephan Barth 2023-12-26 17:14:36 +01:00
parent a41f5fb72a
commit f312ad57db
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package Manticore::Num::ContinuedFraction;
# lazy and potential infinite continued fraction
use strict;
use warnings;
use Math::BigRat;
# Approximation object:
# {
# a => BigRat, this integer
# r => remainder, input number; undef if fraction has ended
# c => child, better approximation (or undef)
# e => end of list?
# }
sub new {
my ($pkg, $x) = @_;
die "ContinuedFraction can only be constructed of positive numbers!" if $x<0;
my $prop = int $x;
if(0 == $prop) {
return undef; # TODO
}
my $rem = $x - $prop;
return bless {
a => $prop,
r => $rem,
}
}
sub child {
my $self = shift;
if(not $self->{c}) {
my ($a, $r) = @{$self}{qw(a r)};
my $c = Manticore::Num::ContinuedFraction->new(1/$r);
$self->{c} = $c;
}
return $self->{c}
}
1;

20
tests/testCf.pl Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env perl
use strict;
use warnings;
use Math::Trig;
use Data::Dumper;
BEGIN {
push @INC, '..'
}
use Manticore::Num::ContinuedFraction;
my $pi = Manticore::Num::ContinuedFraction->new(pi);
print $pi->child();
print Data::Dumper::Dumper($pi);