Archive for the ‘Uncategorized’ Category

Now that Math::BigInt mostly works (still no negative numbers, alas), I thought I’d take a stab at FatRat. My first step (after creating Math-FatRat on github) was to copy the source code for Rat. After all, FatRat is mostly the same thing, only with Math::BigInt instead of Int.

And at that point, I wanted to calculate gcd, and the best way to do that was to get a function from Math::BigInt, since Math::BigInt can call directly into the BigDigits library. While I waited for TimToady to give me permission to add a gcd function to Perl 6, I looked for another way to create useful FatRat objects. And hey, it occurred to me that you might well want to create a FatRat from a normal Rat. So…

I did eventually get permission for gcd, and while I haven’t added it to Rakudo or the spec yet, I did add it to Math::BigInt so I could use it here. Plowing on from there it was simple to get to infix:<+>. And that’s where the real trouble started.

So, while working on Math::BigInt, I discovered that I couldn’t declare the arithmetic operators to be “our”, else they would block the visibility of Rakudo’s basic arithmetic operators. (Pretty sure that’s a bug.)

But the situation seems to be even worse with Math::FatRat. If I define

I’ve added Math::BigInt to the ecosystem. It’s still a pain in the neck to install the BigDigits library (“libbd”), but I used GNU Autotools to generate a configure and make solution that will build the library and install it for you. (Instructions are in the README.) At least, on OS X and Linux and probably other Unix-y platforms; I’m not sure if it will work on Windows or not. (Does Zavolaj work on Windows?)

Now that I’ve got the unpleasant part out of the way (and learned a ton about Autotools in the process, it’s actually quite easy to use), I can get to playing with Math::FatRat…

Spent the evening fighting with GNU Automake, trying to generate a portable build setup for BigDigits. Got one that works beautifully under OS X, which was very exciting. Alas, it does not work for me under Linux. Will try to sort this out tomorrow, but it may be a while, since I’m taking my son to the circus.

At this point, Math::BigInt is working, modulo a few issues with meta-operators that seem to revolve around Rakudo bugs. I have implementations of the basic operators and comparison operators, though they probably could use some more tests. I took sorear++’s suggestion to use postfix L as the shortcut for creating BigInts. That lets you say things like

The catch here is that these new operators don’t work properly with Rakudo’s meta-ops:

> say [*] 1L .. 40L;
8.15915283247898e+47

The result should be a much longer integer rather than a Num, like this:

> say reducewith(&infix:<*>, 1L .. 40L); # this is what [*] should be doing internally
815915283247897734345611269596115894272000000000

But [*] doesn’t see our new operators, so it calls the Real version of the operator, which in turn calls Math::BigInt.Bridge. That creates a Num version of the BigInt that Rakudo knows how to multiply, though of course, a lot of precision is lost in the process.

As a different approach to trying to meta-ops to work, I’ve also added L+ and L* operators. The idea was that these do BigInt calculations even if both of their arguments are regular Ints:

I suspect everyone who plays around with numerical problems on Perl 6 has been as frustrated as I am not to have arbitrary precision integers in Rakudo. As a sort of first step toward getting them, I’ve thrown together the beginnings of a Math::BigInt module using the BIgDigit multiple-precision arithmetic library and Zavolaj.

(Why BigDigit instead of GMP? Two simple reasons. First, building GMP failed on my main development machine (OS X 10.5). GMP’s suggestion for fixing the problem involved getting a new main development environment for the machine, which seemed like a major pain in the neck, and didn’t impress me with GMP’s portability. Second, GMP’s main multiple-precision type is a C struct you store on the stack. That means using it with Zavolaj would have required creating wrappers for every GMP function I wanted to use. Yuck.)

From which you can quickly conclude two things: Math::BigInts easily worked with the sequence operator. And creating a Math::BigInt is ugly and awkward. Once again, blogging has forced me to confront the limitations of my code.

So… if I had an operator to create a BigInt, the code would look a lot nicer. What’s more, you could avoid the term Math::BigInt actually appearing in your code, making it very easy to port to Perl 6s which actually support arbitrary precision Ints. Clearly then, I need to figure out a symbol to use…

I’d been thinking for a while that I should look at adding the extended standard math library functions to Perl 6. And I’d been thinking I should try to do something with Zavolaj, the Perl 6 native call interface. And gee, those two things work perfectly together!

So, my solution for Masak’s p1 has the distinction of being by far the least efficient working solution. Which is a shame, because I think this one was my favorite solution of the contest. It may be slow, and I’d never advise anyone to use it for anything practical (given the other, much more efficient solutions), but in my opinion it’s a charming piece of code.

The key organizational piece for my solution is the Ordering class. (BTW, I didn’t like that name at all, it’s probably my least favorite part of my solution. My theory is Masak was too awestruck by my inefficiency to quibble about the name.) I was striking about for how to represent a series of matrix multiplications, and hit on the idea of using a very simple stack-based language to do it. The language has two operations: an Int represents putting the matrix with that index on the stack. The string "*" represents popping the top two matrices on the stack, multiplying them, and pushing the result back on the stack. Here’s the code for making that happen while tracking the total number of multiplications:

This time instead of a stack of Pairs (for the matrix size), we have a stack of Str representing each sub-matrix’s name. At the end we pop the last thing on the stack, and it’s the string representing the entire multiplication. And by making this Ordering.Str, any time you print an Ordering you get this nice string form — handy both for the desired output of the program and for debugging.

I won’t comment on the guts of the generate-orderings function, which is heavily borrowed from HOP via List::Utils. Just note that given the number of matrices, it lazily generates all the possible permutations — both the source of my code’s elegance and its extreme inefficiency.

Oonce you’ve got the array @matrices set up, calculating and reporting the best ordering (very slowly!) is as simple as

So, that’s simple enough, right? TimesPi stores a Real number $.x internally, and the value it represents is that number times pi. There’s a postfix operator π to make it really easy to construct these numbers. Because we’ve defined a Bridge method, this class has access to all the normal methods and operators of Real. Still, as presented above it is pretty useless, but defining some operators hints at a useful purposes for this class.

With these operators in place, basic arithmetic involving TimesPi numbers will stay in the TimesPi class when appropriate. For instance, if you add two TimesPi numbers, the result will be a TimesPi. The cool thing about this is that it is as exact $.x values allow, rather than forcing everything to be a floating point calculation of limited accuracy.

We can even take things a step further, using this to perform exact trig calculations:

is unreadable gibberish or not, with the following Haskell suggested as an easier-to-understand version.

fib = 1 : 1 : zipWith (+) fib (tail fib)

(I’ve “corrected” both versions so they start the sequence with 1, 1.)

The first thing to observe here is that this are not the same at all! The Perl 6 version is the Fibonacci numbers less than 100, while the Haskell version lazily generates the entire infinite sequence. If we simplify the Perl 6 to also be the (lazy) infinite Fibonacci sequence, we get the noticeably simpler

my @fib := 1, 1, *+* ... *;

To my (admittedly used to Perl 6) eye, this sequence is about as clean and straightforward as it is possible to get. We have the first two elements of the sequence:

1, 1

We have the operation to apply repeatedly to get the further elements of the sequence:

*+*

And we are told the sequence will go on forever:

... *

The *+* construct may be unfamiliar to people who aren’t Perl 6 programmers, but I hardly think it is more conceptually difficult than referring to two recursive copies of the sequence you are building, as the Haskell version does. Instead, it directly represents the simple understanding of how to get the next element in the Fibonacci sequence in source code.

Of course, this being Perl, there is more than one way to do it. Here’s a direct translation of the Haskell version into idiomatic Perl 6:

my @fib := 1, 1, (@fib Z+ @fib[1..*]);

Well, allowing the use of operators and metaoperators, that is, as zipWith (+) becomes Z+ and tail fib becomes @fib[1..*]. To the best of my knowledge no current Perl 6 implementation actually supports this. I’d be surprised if any Perl 6 programmer would prefer this version, but it is out there.

If you’re insistent on writing function calls instead of operators, you could also say it

rokoteko asked on #perl6 about using sequences to calculate arbitrarily accurate values. I’m not sure why he thought I was the expert on this, but I do have some ideas, and thought they should be blogged for future reference.

Note that we don’t try to do this exclusively as a sequence; getting 1, 1/3, 1/5, 1/7... is much easier using map, and then we mix that with the sequence of powers of $x using Z*.

So, one nice thing about the sequence operator is that you can easily use it to get all the Rats in the terms of a Taylor series, because once the terms get small enough, they will switch to Nums. So we can say

I use sorted-merge from List::Utils to merge the two sequences of Taylor series terms into one strictly decreasing (in magnitude) sequence. That, in turn, makes it easy to use the triangle-reduce metaoperator to stop summing the terms when they’ve gotten so small they are no longer representable by a Rat.

What is this good for? Well right now, not much. Sure, we’re gotten a fairly accurate Rat version of pi, but we could have gotten that more quickly and accurately by just saying pi.Rat(1e-15).

But once we have working FatRats, this approach will let us get arbitrarily accurate rational approximations to pi. Indeed, it suggests we could have slow but very accurate ways of calculating all sorts of transcendental functions…