63
\$\begingroup\$

xkcd π comic

Happy π Day. The goal of this question is to calculate the area for a circle of radius 3, where A = πr².

The catch is that you have to use the constant π that is defined in a different language than the one you are programming in. For example, you can write a C program that uses Fortran's MATH::PI, or a Python program that uses Java's java.lang.Math.PI.

Rules:

  • Your code must use a stored value of π from a different language for the calculation. (i.e. it must be stored in a constant or math library.)
  • All of the code for your program must fit in a single file. For example, You cannot write one program in C to print π, then another in Java to run the C program. (However, you can write a Java program that writes and compiles a C program by itself.)
  • You cannot download π from a webpage and claim that your constant came from PHP/ASP/HTML.

Here is an example that runs in Bash, and uses Python's stored math.pi value:

#!/bin/bash
PI=`python -c 'import math; print math.pi'`
bc -l <<< "3 * 3 * $PI"

Output:

28.27433388231

This is a Popularity Contest, so the entry with the most votes after a week wins.

Edit: After one week, the prize goes to DigitalTrauma with 93 points. Thanks for the awesome assembler tip - I did not know that the the FPU stored the constant in hardware. I expected this contest to be about finding funny ways to throw clock cycles away, but that one could actually save a few.

* Image courtesy of: http://xkcd.com/10/

\$\endgroup\$
  • 38
    \$\begingroup\$ It's the 3rd day of the 14th month?? My calendar must be broken. \$\endgroup\$ – Gareth Mar 14 '14 at 17:03
  • 30
    \$\begingroup\$ Next year: 3/14/15 at 9:26 and 53sec, i will post a challenge \$\endgroup\$ – TheDoctor Mar 14 '14 at 22:32
  • 5
    \$\begingroup\$ Ugh. Tau is better. And this. \$\endgroup\$ – bjb568 Mar 15 '14 at 1:54
  • 3
    \$\begingroup\$ @bjb I agree, Tau makes more sense, but that doesn't mean we can't have a little fun in mid march. :) \$\endgroup\$ – undergroundmonorail Mar 15 '14 at 3:40
  • 9
    \$\begingroup\$ How intriguing. On π day, my reputation was 314. \$\endgroup\$ – tbodt Mar 16 '14 at 2:52

43 Answers 43

1
2
2
\$\begingroup\$

Mathematica + R

Needs["RLink`"]
InstallR[]
 = REvaluate["pi"][[1]];
R = 3;
 R^2
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

bash + html + APL

 echo '<html><body><p>&#x25cb;3*2</p></body></html>' | w3m -dump -T text/html | apl -f -
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ruby + Python + C++ + Batch (if you want to include it)

Oh, this took much longer than I wanted it to. As far as I know this will only work on Windows, though if you edit the rm command it may work on Linux.

Here's what it does:

  1. Ruby creates pi.cpp
  2. Ruby runs batch code to compile pi.cpp using MinGW or GCC
  3. Ruby runs pi.exe
  4. Pi.exe runs Python code to find pi
  5. Python saves pi to pi.txt
  6. Ruby reads pi.txt, does the math to find the area, and prints it

Comment out the last line to see the remnants of the process.

p = "\\\"import math; import subprocess; f = open('pi.txt', 'w'); print(math.pi, file=f)\\\""

c = '''#include <iostream>
#include <cstdlib>

int main() 
{ 
    system("python -c '''+p+'''");
    return(0);
}'''

command2 = "g++ pi.cpp -o pi.exe"
command3 = "pi.exe"
command4 = "rm pi.cpp && rm pi.exe && rm pi.txt"

File.open("pi.cpp", "w+") do |file|
    file.puts c
end

system(command2)
system(command3)

my_very_own_pi = ''

File.open("pi.txt", "r") do |file|
    my_very_own_pi = file.gets
end

puts "The answer is: #{(3**2)*(my_very_own_pi.to_f())}"

system(command4)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Obligatory GolfScript+Ruby answer :)

"#{Math::PI*9}"
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ok I'll bite...

AWK + PHP

$ awk -v PI=`php -r 'echo pi();'` 'BEGIN{print 3*3*PI}'

PHP + AWK

$ php -r "echo 3*3*`awk 'BEGIN{printf 4*atan2(1,1)}'`;"

BASH + PHP

$ PI=$(php -r 'echo pi();');C=$((${PI/\./}*3*3));echo ${C:0:2}.${C:2}

nJoy!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

ASP.net / JS

alert(3*3*<%Response.Write(Math.PI)%>)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Matlab & Python

[~, pi] = system('python -c "import math; print(math.pi)"');
area = str2num(pi) * 3^2;
disp(area)

Output:

28.274333882308138
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Groovy + Java (Someone had to do it... :) )

println java.lang.Math.PI * 3 * 3
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Java & JavaScript

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
    public static void main(String[] args) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        try {
            System.out.println((double)engine.eval("Math.PI") * 3 * 3);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C# and VB.NET

This one creates a VB.NET assembly on the fly (using Microsoft CodeDom) to get the value of Pi. No need to invoke shells, external interpreters, or any of those other tricks. You get two languages, not just in a single process, but in a single thread!

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Microsoft.VisualBasic;

namespace PiDay2014CSharpConsole
{
    public class AreaCalculator
    {
        private double Pi()
        {
            StringBuilder vb = new StringBuilder();
            vb.AppendLine("Public Class PiDay");
            vb.AppendLine("    Public Function VbPi() As Double");
            vb.AppendLine("        Return System.Math.PI");
            vb.AppendLine("    End Function");
            vb.AppendLine("End Class");
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new VBCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, vb.ToString());
            var piDay = cr.CompiledAssembly.CreateInstance("PiDay");
            Type t = piDay.GetType();
            object result = t.InvokeMember("VbPi",
               BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
               null, piDay, null);
            return (double)result;
        }

        public double CalculateArea(double radius)
        {
            return Pi() * radius * radius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            AreaCalculator calc = new AreaCalculator();
            Console.Out.WriteLine("{0}", calc.CalculateArea(3.0));
            Console.In.ReadLine();
        }
    }
}

Output:

28.2743338823081

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Ruby+Python

require 'bigdecimal'
require 'bigdecimal/util'
File.open("pi.py", 'w') {|f| f.write("import math\nfrom decimal import *\ngetcontext().prec = 100\nprint Decimal(math.pi)") }
puts %x(python pi.py).to_d*3*3
%x(rm pi.py)

result:

0.28274333882308138043981671216897666454315185546875E2
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Python and Java? Please specify the language in your title as #Language# \$\endgroup\$ – user10766 Mar 17 '14 at 22:51
1
\$\begingroup\$

HTML + JAVASCRIPT

<label>Price 1</label><input type="text" class="price" /><br/>
<label>Price 1</label><input type="text" class="price" /><br/>
<label>Total</label><input type="text" id="total" /><br/>
<script>
var $prices=$('.price').keyup(calcTotal);
function calcTotal(){
  var tot=Math.PI;
  $prices.each(function(){
      tot*=$(this).val() | 0;
    });
   $('#total').val( tot);  
}
</script>
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Umm, jQuery isn't a "language." You're using JavaScript's Math.PI from... JavaScript? \$\endgroup\$ – BAF Mar 17 '14 at 16:09
  • \$\begingroup\$ ok. edited. thanks. \$\endgroup\$ – Sp0T Mar 18 '14 at 4:15
0
\$\begingroup\$

x86 Assembly Language

NASM syntax

global _start

section .data
val: dq 3.0

section .text

_start:

fldpi
fld qword [val]
fmul st0,st0
fmul st1,st0
| improve this answer | |
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.