Raku Challenge Week 4, Task 1: Printing π

Let me return to the old challenges from last year and fill a few more gaps. The task for now is to write a program to output the same number of π digits as the size of the program.

Let me return to the old challenges from last year and fill a few more gaps.

The tasks reads:

Write a program to output the same number of PI digits as the size of your script. Say, if your program size is 10, it should print 3.141592653.

OK, I immediately have a few ideas:

  • Just type the digits in the program and fit the width.
  • Use some kind of formatting output.
  • Compute the value of π and print it.

The first option contains a paradox. The program must keep need to keep all the digits that you need to print but you also need a printing instruction. So the file length will always be bigger. The only exception is when you are using REPL:

$ raku
> 3.14

The second option is more promising. In Raku, there are at least printf and fmt. Let us see how many digits we can potentially use. The only place where you can see a substring 3.1415 in the Rakudo sources seems to be the file gen/moar/CORE.c.setting:

my constant pi  = 3.14159_26535_89793_238e0;

Looks like we have enough digits. Can we then print π.fmt('%.20f') and see all of them?

> π.fmt('%.20f')

Oops. Not that promising any more. But let’s try to make the output shorter then. After a few attempts you get it:

> π.fmt('%.12f')

Hmm, the width is perfect but there’s a zero in the last position? OK, let’s use an ASCII version to add a character and remove that zero:

> pi.fmt('%.11f')

Ah, no, when switching from π to pi, you need to add digits, not to remove them. And if you add, you’ll get zeroes. And did we forget that we are in the REPL, and for a real program in a file we need to add at least four characters to add say?

OK, move on to the third option maybe? In the third option, we can use one of the known algorithms to compute the value of π to any arbitrary length, and then our program can in theory be as big as we want, including detecting its size by calling system functions.

Good one. But what if you just print π?

say π

Run this program and confirm that you get quite a few digits:

$ raku ch-1.raku 

Aha, we’ve got a five-character program and 17 characters in the output. OK, let us just add some ‘useful’ noise to the code until it grows to the sam 18 characters.

print(pi ~ "\n");

Yes! Now there are exactly 17 characters. The program looks ugly but does the job and satisfies the conditions, so the task has been solved, congratulations!

* * *

→ GitHub repository
→ Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *