pc88mxer has asked for the wisdom of the Perl Monks concerning the following question:
I immediately thought it would be interesting to compute this exactly as a fraction and also to generalize the problem by replacing 30 with an arbitrary integer n. I knew perl had support for arbitrary precision integers, and I was curious to find out if the numerators or denominators formed any recognizable pattern.30 29 1 ---- + ---- + ... + ---- 1 2 30
So when I got home I consulted the documentation for bigrat, and naively coded up this loop:
Needless to say, it didn't work as I expected - I got output like this:use strict; use warnings; use bigrat; for my $n (1..30) { my $s = 0; for my $k (1..$n-1) { $s += $k / ($n-$k); } print "n = $n, s = $s\n"; }
I expected to get 5/2 for n = 3 and 13/3 for n = 4, etc. After reconsulting the docs and some more experimentation, I finally came up with this solution:n = 1, sum = 0 n = 2, sum = 1 n = 3, sum = 2.5 n = 4, sum = 4.333333333333333
which gave what I wanted:for my $n (1..30) { my $s = 0; for my $k (1..$n-1) { $s += 1/1 * $k / ($n-$k); } print "n = $n, s = $s\n"; }
Having tackled that problem, I went on to extract the numerator and denominator sequences so I could plug them into The On-Line Encyclopedia of Integer Sequences. Again, my naive approach was to simply call ->numerator and ->denominator on each sum:n = 1, sum = 0 n = 2, sum = 1 n = 3, sum = 5/2 n = 4, sum = 13/3
Alas, I ran into problems on the very first term:for my $n (1..30) { ... push(@nums, $s->numerator); push(@denoms, $s->denominator); }
Indeed, this program illustrates the problem:Can't locate object method "numerator" via package "Math::BigInt" at . +/frac line ...
So I guess my questions are:use bigrat; my $x = 1; print $x->numerator, "\n";
Update 1: fixed typo with expected results.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: issues using bigrat
by ikegami (Patriarch) on May 11, 2008 at 18:04 UTC | |
|
Re: issues using bigrat
by perl-diddler (Chaplain) on May 11, 2008 at 21:03 UTC | |
by ikegami (Patriarch) on May 11, 2008 at 21:08 UTC | |
by perl-diddler (Chaplain) on May 11, 2008 at 21:47 UTC | |
by ikegami (Patriarch) on May 11, 2008 at 22:15 UTC | |
|
Re: issues using bigrat
by perl-diddler (Chaplain) on May 11, 2008 at 21:38 UTC | |
|
Re: issues using bigrat
by perl-diddler (Chaplain) on May 11, 2008 at 21:57 UTC | |
by pc88mxer (Vicar) on May 11, 2008 at 23:26 UTC | |
by perl-diddler (Chaplain) on May 12, 2008 at 03:00 UTC | |
by pc88mxer (Vicar) on May 12, 2008 at 05:40 UTC |