in reply to issues using bigrat

Works for me...?

I read the problem description you gave (summing the series), and wrote a "1-liner" (iterative 'bashing') which seems to work exactly as you describe. I am using the ".." operator just as you are, so I don't think you need to use the "C" style "for" loop. Not yet sure why things aren't working the same for you (am using 5.8.8, here, as well). Original "1-liner format:"

perl -e 'use bigrat;for my $n (1..5){my $s=0;for my $i (1..$n) {$s+=($ +n+1-$i)/$i} push @nums, $s->numerator; push @dens, $s->denominator; $ +num=$s->numerator; $den=$s->denominator; print "n = $n, s = $s, num=$ +num, den=$den\n";} print "nums=",(join ", ",@nums), "\n"; print "dens +=",(join ", ",@dens),"\n";'
Or pretty-i-fied:
#!/usr/bin/perl -w use bigrat; for my $n (1 .. 5) { my $s = 0; for my $i (1 .. $n) {$s += ($n + 1 - $i) / $i} push @nums, $s->numerator; push @dens, $s->denominator; $num = $s->numerator; $den = $s->denominator; print "n = $n, s = $s, num=$num, den=$den\n"; } print "nums=", (join ", ", @nums), "\n"; print "dens=", (join ", ", @dens), "\n";
Did you convert some 'bignum' type to an integer somewhere? I'll have to study your code more closely to find out where it's breaking, but thought I'd at least offer something that seemed to do what you wanted in the way you wanted...:-)
-Linda

Replies are listed 'Best First'.
Re^2: issues using bigrat
by ikegami (Patriarch) on May 11, 2008 at 21:08 UTC

    You changed
    $s += $k / ($n-$k);
    to
    $s += ($n + 1 - $i) / $i;

    The "+ 1" has the same effect as the "1 *" the OP used in his fixed version. Just like him, your $n and $i are plain integers, not big ints.

      Yeah, you might think so, but if my code has the same problem, why does it not suffer the same problem calling numerator or denominator on "$s"?

      I mean the output is, I believe, what would expect if it was working correctly:

      n = 1, s = 1, num=1, den=1 n = 2, s = 5/2, num=5, den=2 n = 3, s = 13/3, num=13, den=3 n = 4, s = 77/12, num=77, den=12 n = 5, s = 87/10, num=87, den=10 nums=1, 5, 13, 77, 87 dens=1, 2, 3, 12, 10
      Hmmm...not sure but it may that the original example that "worked" didn't really produce the right output or wasn't doing the right computation.

        why does it not suffer the same problem calling numerator or denominator on "$s"?

        "Same problem"? His doesn't suffer from such a problem either. Both your results and his are BigRats

        Update: Bad test. And you've already answered yourself.