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\$
14
  • 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\$ 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

129
\$\begingroup\$

C + x86 assembly

Not satisfied with a constant defined in the software of your language? Why not use a language that can access a constant value of PI right from your FPU hardware:

#include <stdio.h>

int main (int argc, char **argv) {
    double pi;
    __asm__("fldpi" : "=t" (pi));
    printf("%g\n", 3 * 3 * pi);
    return (0);
}
\$\endgroup\$
9
  • 67
    \$\begingroup\$ Holy crap, there's an instruction just to load the value of pi. \$\endgroup\$ Mar 15 '14 at 8:05
  • 21
    \$\begingroup\$ x86 has instructions for EVERYTHING. \$\endgroup\$
    – fluffy
    Mar 16 '14 at 7:32
  • 7
    \$\begingroup\$ @user2357112 There are 7 instructions just for loading "commonly used constants" \$\endgroup\$ Mar 16 '14 at 17:20
  • 7
    \$\begingroup\$ Good choices for the 7 constants, too! I'm always using log_e(2), but not, say, 2. \$\endgroup\$
    – Tim S.
    Mar 18 '14 at 16:56
  • 4
    \$\begingroup\$ @fluffy my x86 core is broken: I tried MOV AX, c0ffe; ADD MILK; ADD SUGAR; ADD SUGAR; MOV ecx, c0ffe; MOV ebx,1; MOV eax,4 and my bios speaker laughed at me..... \$\endgroup\$
    – GMasucci
    Dec 4 '14 at 10:25
78
\$\begingroup\$

Python, bash, C, J, PHP and Python3

import subprocess

p = subprocess.Popen("""
echo '
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <math.h>

int main(int pi) {
    if (pi == 1) printf("%.5f", M_PI);
    if (pi == 2) printf("o. 1");
    if (pi == 3) printf("<?php printf(\\"%%.5f\\", pi()); ?>");
    if (pi == 4) printf("import math; print(\\" %%.5f\\" %% math.pi)");
    return 0;
}
' > gcc -o pi
./pi
./pi J | jc
./pi and PHP | php
./pi and Python 3 | python3
""", shell=True, stdout=subprocess.PIPE)

values_of_pi = map(float, map(str.strip, p.stdout.read().split()))
pi = max(values_of_pi, key=values_of_pi.count)

print pi * 3 * 3

Just to be safe, this program retrieves pi from a few different languages, taking the most agreed upon value. More languages can easily be added for greater reliability.

\$\endgroup\$
5
  • 28
    \$\begingroup\$ I just threw up a little in my mouth. \$\endgroup\$ Mar 14 '14 at 19:10
  • \$\begingroup\$ What's J and why are you running your C program with it? \$\endgroup\$
    – NoBugs
    Mar 16 '14 at 5:41
  • \$\begingroup\$ @NoBugs J is another language, and I'm running it (jc is the J console on my computer) with output from my C program (o. 1) to get another value of pi. The arguments aren't important. \$\endgroup\$
    – grc
    Mar 16 '14 at 5:52
  • 1
    \$\begingroup\$ echo $long_string > gcc -o pi? I can't believe no one caught this. Also, have you heard of here-docs|here-strings? \$\endgroup\$ Mar 16 '14 at 21:52
  • \$\begingroup\$ This is one of the coolest pieces of code I have ever seen. I am going to frame this and put it on my wall. Possibly with a warning. \$\endgroup\$
    – Kevin
    Mar 21 '14 at 15:34
41
\$\begingroup\$

PHP/MYSQL

$link = mysqli_connect("localhost", "user", "password", "dbname");
$query = mysqli_query($link, 'SELECT PI() AS pi');
$row = mysqli_fetch_assoc($query);
echo 3*3*$row['pi'];
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Very clever. Using a very standard way of interfacing different runtimes. =) +1 \$\endgroup\$
    – jpmc26
    Mar 14 '14 at 19:11
34
\$\begingroup\$

Perl/Tk with C, Pascal, Java, JavaScript, LaTeX3, Prolog, Perl, Scheme, Lua, Python, TeX/PGF

The following Perl script displays a windows that lists the values of π and the calculated area. The value of π is taken from different languages as shown below.

Result

The one-file script:

#!/usr/bin/env perl
use strict;
$^W=1;

use Tk;
use Tk::Font;
use Tk::HList;
use Tk::ItemStyle;
use Tk::PNG;

# Function to calculate the area of the circle with radius 3
sub A ($) {
    use bignum;
    return 9*$_[0];
}

my $title = 'Pi Day';

# Configuration of external program names
my %prg = qw[
    Pascal fpc
    Perl perl
    Prolog swipl
    Scheme guile1
    TeX  tex
    LaTeX latex
];
sub prg ($) {
    my $prg = shift;
    return $prg{$prg} // $prg;
}

# Column headers
my @header = (
    '',
    'Language',
    "\N{U+03C0}",
    "A(3) = A(r) = \N{U+03C0}\N{U+2009}r\N{U+00B2}",
);

my $mw = MainWindow->new(
    -title => $title,
);

# Font setup (larger font)
my $font_size = '22';
my $font = $mw->Font();
$font->configure(-size => $font_size);

# ---------
# Utilities
# ---------

# Run program in backticks, quote arguments if needed and some error checking
sub backticks_pi (@) {
    my @cmd = map{/[ ()$;<>|\x22]/ && length > 1 ? "'$_'" : $_} @_;
    print "[@cmd]\n";
    my $catch = `@cmd`;
    if ($? == -1) {
        warn "Failed to execute: $!\n";
    }
    elsif ($? & 127) {
        warn sprintf "Child died with signal %d!\n", $? & 127;
    }
    elsif ($?) {
        warn sprintf "Child exited with value %d!\n", $? >> 8;
    }
    else {
        return $1 if $catch =~ /^\s*(\d+\.\d+)\s*$/
                  or $catch =~ /\bpi\s*=\s*(\d+\.\d+)/;
    }
    warn "Could not find pi in the output of \"@cmd\"!\n";
    return 0;
}

# Run a program with error checking
sub run_cmd (@) {
    print "[@_]\n";
    system @_;
    if ($? == -1) {
        warn "Failed to execute: $!\n";
    }
    elsif ($? & 127) {
        warn sprintf "Child died with signal %d!\n", $? & 127;
    }
    elsif ($?) {
        warn sprintf "Child exited with value %d!\n", $? >> 8;
    }
    else {
        return $1;
    }
    return undef;
}

# Create a bitmap logo
sub make_logo ($$$@) {
    my $name = shift;
    my $logo = shift;
    my $contents = shift;
    my $file = "piday-logo-$name.tmp";
    if ($contents) {
        open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!";
        print OUT $contents;
        close(OUT);
    }
    foreach (@_) {
        run_cmd @$_;
    }
    return $mw->Photo(
        -file => $logo,
    ) if -f $logo;
    return undef;
}

# Call foreign language to calculate pi
sub make_pi ($$@) {
    my $file = shift;
    my $source = shift;
    if ($source) {
        open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!";
        print OUT $source;
        close(OUT);
    }
    my $cmd_last = pop;
    foreach (@_) {
        run_cmd @$_;
    }
    return backticks_pi @$cmd_last;
}

# Add result list table
my $h = $mw->HList(
    -header  => 1,
    -columns => scalar @header,
    -width   => 100,
    -height  => 20,
    -font    => $font,
)->pack(
  -expand => 1,
  -fill => 'both',
);

# Add header for the result list table
for (0 .. @header-1) {
    $h->header('create', $_,
        -text => $header[$_],
    );
}

# Exit button
my $quit = $mw->Button(
    -text => 'Quit',
    -command => sub {exit},
    -font => $font,
)->pack;


my @list;
my @cmd;
my $pi;
my $source;
my $img;

# GNU C
# -----

$img = make_logo(
    'C',
    'piday-logo-c.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-c-gccegg.png',
        'http://gcc.gnu.org/img/gccegg-65.png',
    ],
    [
        prg('convert'),
        '-scale', '54x64',
        'piday-logo-c-gccegg.png',
        'piday-logo-c.png',
    ],
);

$source = <<'END_SOURCE';
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>

#define xstr(s) str(s)
#define str(s) #s

int main() {
  long double pi = M_PI;
  printf("pi=%s", xstr(M_PIl));
  return 0;
}
END_SOURCE

$pi = make_pi(
    'piday-c.c',
    $source,
    [
        prg('gcc'),
        '-o', 'piday-c',
        'piday-c.c',
    ],
    [
        prg('./piday-c')
    ],
);

push @list, {
    language => 'GNU C',
    pi       => $pi,
    image    => $img,
};

# Java
# ----

$img = make_logo(
    'Java',
    'piday-java.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-java.svg',
        'https://upload.wikimedia.org/wikipedia/commons/a/a4/Java_logo_and_wordmark.svg',
    ],
    [
        prg('convert'),
        '-scale', '35x64',
        'piday-java.svg',
        'piday-java.png',
    ],
);

$source = <<'END_SOURCE';
public class PiDayJava {
    public static void main(String args[]) {
        System.out.println(Math.PI);
    }
}
END_SOURCE

$pi = make_pi(
    'PiDayJava.java',
    $source,
    [
        prg('javac'),
        'PiDayJava.java',
    ],
    [
        prg('java'),
        'PiDayJava',
    ],
);
push @list, {
    language => 'Java',
    pi       => $pi,
    image    => $img,
};

# Perl
# ----

# Math/Complex.pm: sub pi () { 4 * CORE::atan2(1, 1) }
@cmd = (prg('Perl'), '-e', 'use Math::Complex; print pi');
$pi = backticks_pi @cmd;

my $img = Tk->findINC('Camel.xpm');
$img = $mw->Photo(
    -file => $img,
);

push @list, {
    language => 'Perl',
    pi => $pi,
    image => $img,
};

# Python
# ------

@cmd = (
    prg('echo'),
    'import math;print math.pi',
    '|',
    prg('python'),
);
$pi = backticks_pi @cmd;

$img = make_logo(
    'python',
    'piday-logo-python.png',
    '',
    [
        prg('wget'),
        '-O',
        'piday-logo-python-master.png',
        'http://www.python.org/static/community_logos/python-logo-master-v3-TM.png',
    ],
    [
        prg('convert'),
        '-crop', '111x111+79+33',
        'piday-logo-python-master.png',
        'piday-logo-python-crop.png'
    ],
    [
        prg('convert'),
        '-scale', '64x64',
        'piday-logo-python-crop.png',
        'piday-logo-python.png',
    ],
);

push @list, {
    language => 'Python',
    pi => $pi,
    image => $img,
};

# TeX
# ---

@cmd = (
    prg('TeX'),
    '\input pgf \pgfmathparse{pi}\message{pi=\pgfmathresult}\end',
);
$pi = backticks_pi @cmd;
my $img = make_logo(
    'tex',
    'piday-logo-tex.png',
    '',
    [
        prg('pdftex'),
        '\mag=4000 \nopagenumbers\font\sc=cmcsc10 \sc pgf\bye'
    ],
    [
        prg('pdfcrop'),
        'texput.pdf',
        'piday-logo-tex.pdf',
    ],
    [
        prg('convert'),
        'piday-logo-tex.pdf',
        'piday-logo-tex.png',
    ]
);
push @list, {
    language => 'TeX/PGF',
    pi => $pi,
    image => $img,
};

# LaTeX3
# ------

my $logo_source = <<'END_LOGO';
\mag=4000
\documentclass{article}
\usepackage{hologo}
\pagestyle{empty}
\begin{document}
\hologo{LaTeX3}
\end{document}
END_LOGO

$img = make_logo(
    'latex3',
    'piday-logo-latex3.png',
    $logo_source,
    [
        prg('pdflatex'),
        'piday-logo-latex3.tmp'
    ],
    [
        prg('pdfcrop'),
        'piday-logo-latex3.pdf',
        'piday-logo-latex3-crop.pdf',
    ],
    [
        prg('convert'),
        'piday-logo-latex3-crop.pdf',
        'piday-logo-latex3.png',
    ]
);
$source = <<'END_LATEX3';
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\msg_term:n { pi=\fp_eval:n { pi } }
\ExplSyntaxOff
\stop
END_LATEX3
$pi = make_pi(
    'piday-latex3.tex',
    $source,
    [
        prg('LaTeX'),
        'piday-latex3.tex',
    ],
);
push @list, {
    language => 'LaTeX3',
    pi => $pi,
    image => $img,
};

print "****************\n";

# Lua
# ---

$img = make_logo(
    'Lua',
    'piday-logo-lua.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-lua.gif',
        'http://www.lua.org/images/lua-logo.gif',
    ],
    [
        prg('convert'),
        '-scale', '64x64', # '50x50',
        'piday-logo-lua.gif',
        'piday-logo-lua.png',
    ],
);

$source = 'print(math.pi)';
$pi = make_pi(
    'piday-lua.lua',
    $source,
    [
        prg('texlua'),
        'piday-lua.lua',
    ]
);
push @list, {
    language => 'Lua',
    pi => $pi,
    image => $img,
};

# JavaScript
# ----------

$img = make_logo(
    'JavaScript',
    'piday-logo-javascript.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-rhino.jpg',
        'https://developer.mozilla.org/@api/deki/files/832/=Rhino.jpg',
    ],
    [
        prg('convert'),
        '-scale', '127x64',
        'piday-logo-rhino.jpg',
        'piday-logo-javascript.png',
    ],
);

$source = 'print(Math.PI)';
$pi = backticks_pi(
    prg('java'),
    '-cp', prg('js.jar'),
    'org.mozilla.javascript.tools.shell.Main',
    '-e', $source,
);
push @list, {
    language => 'JavaScript',
    pi => $pi,
    image => $img,
};

# Scheme
# ------

$img = make_logo(
    'Scheme',
    'piday-logo-scheme.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-lambda.svg',
        'https://upload.wikimedia.org/wikipedia/commons/3/39/Lambda_lc.svg',
    ],
    [
        prg('convert'),
        '-scale', '64x64',
        'piday-logo-lambda.svg',
        'piday-logo-scheme.png',
    ],
);
$source = '(display (* 2 (acos 0)))';
$pi = backticks_pi(
    prg('Scheme'),
    '-c', $source,
);
push @list, {
    language => 'Scheme',
    pi => $pi,
    image => $img,
};

# Prolog
# ------

$img = make_logo(
    'Prolog',
    'piday-logo-prolog.png',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-swipl.png',
        'http://www.swi-prolog.org/icons/swipl.png',
    ],
    [
        prg('convert'),
        '-scale', '78x64',
        'piday-logo-swipl.png',
        'piday-logo-prolog.png',
    ],
);
$source = ":- format('~15f~n', [pi]).\n";
$pi = make_pi(
    'piday-prolog.pro',
    $source,
    [
        prg('Prolog'),
        '-c', 'piday-prolog.pro',
    ]
);
push @list, {
    language => 'Prolog',
    pi => $pi,
    image => $img,
};

# Pascal
# ------

$img = make_logo(
    'Pascal',
    'piday-logo-pascal.gif',
    '',
    [
        prg('wget'),
        '-O', 'piday-logo-pascal.gif',
        'http://www.freepascal.org/pic/logo.gif',
    ]
);
$source = <<'END_PASCAL';
program piday_pascal;

uses sysutils, math;

begin
  writeln(format('%.16f', [pi]));
end.
END_PASCAL
$pi = make_pi(
    'piday-pascal.pas',
    $source,
    [
        prg('Pascal'),
        'piday-pascal.pas',
    ],
    [
        prg('./piday-pascal'),
    ]
);
push @list, {
    language => 'Pascal',
    pi => $pi,
    image => $img,
};

# Sort and fill the table rows
@list = sort {
    my $diff = (length $b->{'pi'} <=> length $a->{'pi'});
    return $diff if $diff;
    return "\L$a->{'language'}\E" cmp "\L$b->{'language'}\E";
} @list;

foreach my $x (@list) {
    my $e = $h->addchild("");
    my $col = 0;
    if ($x->{'image'}) {
        $h->itemCreate($e, $col++,
            -itemtype => 'image',
            -image => $x->{'image'},
        );
    }
    else {
        $col++;
    }
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => $x->{'language'},
    );
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => $x->{'pi'},
    );
    $h->itemCreate($e, $col++,
        -itemtype => 'text',
        -text => A $x->{'pi'},
    );
}

MainLoop;

__END__

Languages

The following list shows the languages and the code that is used to get π.

  • GNU C: GNU extensions are used to get a higher precision of π.

    #define _GNU_SOURCE
    #include <math.h>
    #include <stdio.h>
    
    #define xstr(s) str(s)
    #define str(s) #s
    
    int main() {
        long double pi = M_PI;
        printf("pi=%s", xstr(M_PIl));
        return 0;
    }
    
  • Pascal: Compiled with Free Pascal.

    program piday_pascal;
    
    uses sysutils, math;
    
    begin
      writeln(format('%.16f', [pi]));
    end.
    
  • Java:

    public class PiDayJava {
        public static void main(String args[]) {
            System.out.println(Math.PI);
        }
    }
    
  • JavaScript: Rhino is used for executing JavaScript.

    print(Math.PI)
    
  • LaTeX3:

    \documentclass{article}
    \usepackage{expl3}
    \ExplSyntaxOn
    \msg_term:n { pi=\fp_eval:n { pi } }
    \ExplSyntaxOff
    \stop
    
  • Prolog: SWI Prolog is used as Prolog compiler.

    :- format('~15f~n', [pi]).
    
  • Perl: For fun and completeness.

    use Math::Complex;
    print pi;
    
  • Scheme: The uses Scheme implementation is GNU Guile.

    (display (* 2 (acos 0)))
    
  • Lua: texlua is used as Lua interpreter.

    print(math.pi)
    
  • Python:

    import math
    print math.pi
    
  • TeX/PGF: π is taken from its definition of package pgf and plain TeX is used as TeX format:

    \input pgf
    \pgfmathparse{pi}
    \message{pi=\pgfmathresult}
    \end
    
\$\endgroup\$
16
\$\begingroup\$

dg

print ((import '/math/pi')*3**2)

How it works:

dg is a language that compiles to CPython bytecode. Conveniently, it's compatible with python libraries. import statements in dg return the object they're importing, so this program basically does this:

print (<PYTHON'S MATH.PI>*3**2)

 

 

No, I don't expect any upvotes. :)

\$\endgroup\$
7
  • 4
    \$\begingroup\$ Oopsy daisy, I think I upvoted ;) \$\endgroup\$ Mar 14 '14 at 20:11
  • 1
    \$\begingroup\$ By the way, this is the first thing I ever did in dg. Someone else used it for a golf question and linked to the same place I linked to in this answer. I read it and thought the language looked neat (despite the fact that I despise the doge meme) but didn't plan on using it until about an hour after learning about it, when I read this question and realized I could abuse it. \$\endgroup\$ Mar 15 '14 at 0:06
  • \$\begingroup\$ 5 hours ago, when I posted my first comment, this had but 1 upvote. I think people did take my comment seriously ;) Or they just used yours. \$\endgroup\$ Mar 15 '14 at 1:28
  • \$\begingroup\$ "All the code must fit in a single line". At least some people can read! \$\endgroup\$
    – Floris
    Mar 16 '14 at 12:32
  • \$\begingroup\$ <PYTHON'S MATH.PI> Those repr() strings you get for functions and other objects that don't|can't define their __repr__()s to be valid reconstructions of themselves aren't actually…well…valid. Try __import__('math').pi. \$\endgroup\$ Mar 16 '14 at 22:00
15
\$\begingroup\$

C++ & Lua 5.2

Nothing says overkill quite like embedding an entire language interpreter to access the pi constant.

#include <lua.hpp>
#include <cmath>
#include <iostream>

#define R 3

int main( void )
{
    lua_State* vm = luaL_newstate();

    luaL_openlibs( vm );
    luaL_dostring( vm, "function get_pi() return math.pi end" );
    lua_getglobal( vm, "get_pi" );
    lua_call( vm, 0, 1 );

    lua_Number PI_ = lua_tonumber( vm, -1 );

    std::cout << PI_ * pow( R, 2 ) << std::endl;

    lua_close( vm );
    return 0;
}
\$\endgroup\$
2
  • \$\begingroup\$ could've just... lua_getglobal("math");lua_getfield(-1,"pi"); \$\endgroup\$
    – mniip
    Mar 14 '14 at 14:48
  • \$\begingroup\$ @mniip I realized that after I posted. It's early in the morning and my brain isn't fully operational yet, but this way works just as well so I left it alone. \$\endgroup\$
    – Tony Ellis
    Mar 14 '14 at 14:57
13
\$\begingroup\$

bash + PHP + bc

A fairly simple one-liner:

echo "scale=14;3*3*`php -r 'echo pi();'`"|bc

Output:

28.274333882308
\$\endgroup\$
3
  • \$\begingroup\$ "All the code must fit in a single line". At least some people can read! \$\endgroup\$
    – Floris
    Mar 16 '14 at 12:31
  • 4
    \$\begingroup\$ @Floris: Hate to break it to you, but the question says file, not line. \$\endgroup\$
    – Dennis
    Mar 16 '14 at 16:45
  • 26
    \$\begingroup\$ @dennis - apparently I am not "some people"... :-/ \$\endgroup\$
    – Floris
    Mar 16 '14 at 17:14
10
\$\begingroup\$

MATLAB + Java (21 bytes)

Not sure if MATLAB is cheating, but here we go

java.lang.Math.PI*3^2

Output: Format Short

28.2743

Output: Format Long

28.2743338823081

Formatting type does not affect the value that is stored, it only impacts how it is printed out into the console

\$\endgroup\$
2
  • 1
    \$\begingroup\$ MATLAB.. -shudders- \$\endgroup\$ Mar 18 '14 at 20:41
  • \$\begingroup\$ @theGreenCabbage haha, not sure if that is a good shudder or a bad one :) In my experience it has made writing simple things quickly very easy. Of course there are better alternatives, but if there is not a lot of time, MATLAB does the trick. \$\endgroup\$ Mar 18 '14 at 21:15
10
\$\begingroup\$

Bash, Node, Ruby, Python

#!/bin/bash

node -pe 'Math.PI' \
| ruby -e 'puts ARGF.read.to_f * 3' \
| python -c 'import sys; print(float(sys.stdin.read()) * 3)'
\$\endgroup\$
7
\$\begingroup\$

perl

perl -ne '/M_PI\s*([\d.]*)/&&print $1*3*3' < /usr/include/math.h
\$\endgroup\$
2
  • \$\begingroup\$ +1, even though it doesn't actually work in OS X (math.h includes other files from architecture/*/math.h depending on the target platform) \$\endgroup\$
    – r3mainer
    Mar 14 '14 at 13:46
  • 1
    \$\begingroup\$ Well it doesn't work on Windows either, but I'm not going for portability here :) \$\endgroup\$
    – orion
    Mar 14 '14 at 13:48
7
\$\begingroup\$

Powershell + MS SQL Server

Here is one for Powershell and SQL server (from 2005 up)

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100
$pi=Invoke-Sqlcmd -query "select PI() as sql"
$pi.sql *3*3

and here as a single liner:

add-pssnapin sqlserverprovidersnapin100;add-pssnapin sqlservercmdletsnapin100;(Invoke-Sqlcmd -query "select PI() as sql").sql*3*3

Will post some more later on:)

\$\endgroup\$
7
\$\begingroup\$

JavaScript/PHP

Has to be saved as a *.php file and called in a browser from some server which interprets PHP.

<script type="text/javascript">
    alert(3*3*<?php echo M_PI;?>);
</script>

Could be golfed by using short tags and substituting 3*3 with 9 (is this allowed?):

<script type="text/javascript">
    alert(9*<?=M_PI?>);
</script>

pi() has the same length as M_PI, so there's no winner.

\$\endgroup\$
5
  • 2
    \$\begingroup\$ "is this allowed" - sure, it's not code golf but popularity contest. \$\endgroup\$
    – CompuChip
    Mar 14 '14 at 14:40
  • 1
    \$\begingroup\$ This will not run neither in php nor javascript though. \$\endgroup\$
    – Cthulhu
    Mar 14 '14 at 14:40
  • \$\begingroup\$ Yeah, it needs some <script> tags and a .php extension. \$\endgroup\$
    – CompuChip
    Mar 14 '14 at 16:39
  • 3
    \$\begingroup\$ I edited it although I think it was understandable enough... \$\endgroup\$
    – Reeno
    Mar 14 '14 at 17:55
  • \$\begingroup\$ @Cthulhu "Has to be saved as a *.php file and called in a browser from some server which interprets PHP." Using pure .html or .php or .whatever files won't work, you need apache or something like that. \$\endgroup\$ Mar 15 '14 at 1:29
6
\$\begingroup\$

Emacs Lisp: writing, compiling, and running C

(with-temp-buffer
  (with-temp-file"/#rad.c"(insert"#include<math.h>\n#include<stdio.h>\nint main(void){printf(\"%f\",M_PI*3*3);}"))
  (shell-command"gcc /#rad.c -o /#rad && /#rad"(current-buffer))(string-to-number(buffer-string)))

ungolfed

(with-temp-buffer
  (with-temp-file "/#rad.c"
    (insert"
#include<math.h>
#include<stdio.h>
int main(void){
  printf(\"%f\",M_PI*3*3);
}"))
  (shell-command "gcc /#rad.c -o /#rad && /#rad"
         (current-buffer))
  (string-to-number(buffer-string)))

bonus:

You could triple language this one by running emacs in batch using -eval and surrounding the expression in (print). This would result in Bash running lisp which writes compiles and runs C reads the output and prints it out to your shell in bash.

\$\endgroup\$
5
\$\begingroup\$

For this question, I created my own language,called Digits. The syntax consists of p, a constant representing pi, and digits. When run, it returns all of the digits (and p) multiplied together. Here is my interpreter and code, written in Python:

def interpret(kode):
    out=1.0
    for i in kode:
        if(i=='p'):
            out*=3.14159265
        else:
            out*=int(i)
    return out
print(interpret("p33"))
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Looks to me more like a function in Python than a language, but it works. \$\endgroup\$
    – user10766
    Mar 14 '14 at 20:05
  • 2
    \$\begingroup\$ @hosch250 The python interpreter itself is a (set of) function written in C (in the case of CPython) so this answer is very valid. Quite clever I would say. \$\endgroup\$
    – Juan Campa
    Mar 15 '14 at 21:21
4
\$\begingroup\$

bc + dc + bash (30 chars for the golfers)

Here's a golfy little one:

$ dc<<<"3d*`bc -l<<<'a(1)*4'`*p"
28.27433388230813914596
$ 
  • bc -l<<<'a(1)*4' produces pi (it is stored as a constant in the bc math lib for the a() (arctan) function.
  • dc<<<"3d*pi*p" pushes 3 to the stack, duplicates the value on the top of the stack (3) and multiples, then pushes pi to the stack and multiples, then prints the top of the stack.
\$\endgroup\$
4
\$\begingroup\$

OCaml + awk

Nobody likes OCaml?

  • Use OCaml to compute Pi
  • awk to calculate Pi*r2

Here it is:

ocaml <<< "4.0 *. atan 1.0;;" | awk '/float/{printf("%.12f", 3*3*$NF)}'

The answer is:

28.274333882308
\$\endgroup\$
4
\$\begingroup\$

C++/C

#include <math.h>
#include <iostream>

int main(int argc, char** argv) {
    std::cout << 3*3*M_PI << std::endl;
    return 0;
}
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to the site! But I think the question is looking for a program that actually calls a function or compiles a program in another language, not one that merely will compile in more than one language. \$\endgroup\$ Mar 15 '14 at 12:34
  • 4
    \$\begingroup\$ @JonathanVanMatre: I think in this case he meant that he uses constant from C header in C++. std::cout was never a valid C syntax. \$\endgroup\$ Mar 15 '14 at 13:29
  • \$\begingroup\$ Ah, good call there. \$\endgroup\$ Mar 15 '14 at 14:12
4
\$\begingroup\$

Very simple, uses bash to access the C math library:

bc -l <<< "3 * 3 * `grep -w M_PI /usr/include/math.h | awk '{ print $4 }'`"
\$\endgroup\$
4
\$\begingroup\$

VimScript + Python

:py import math
:ec pyeval("math.py")*3*3

result:

28.274334
\$\endgroup\$
4
\$\begingroup\$

Since Fortran does not actually have an intrinsic value for pi (which is was OP seems to indicate with the statement "Fortran's MATH::PI"), I had to write one for C. I opted, rather than actually defining it, that I'd just determine it using some fast algorithm:

#include <math.h>
double pi_eval(){
    double a = 1.0;
    double b = 1.0/sqrt(2.0);
    double t = 0.25;
    double x = 1.0;
    double y;
    int i;

    for(i=0; i<4; i++){
        y = a;
        a = 0.5*(a+b);
        b = sqrt(b*y);
        t -= x*(y-a)*(y-a);
        x *= 2.0;
    }
    return (a+b)*(a+b)/(4.0*t);
}

(saved as pi_calc.c) Which is then used in area_calc.f90:

program area_calc
   use, intrinsic :: iso_c_binding
   implicit none

   interface
     function pi_eval() bind(c)
       use, intrinsic :: iso_c_binding
       real(c_double) :: pi_eval
     end function pi_eval
   end interface
   real(c_double) :: pi, area

   pi = pi_eval()
   print *,"area=",3.0*3.0*pi

end program area_calc

This outputs the required

 area=   28.2743338823081

One compiles this using

gcc -c pi_calc.c
gfortran -o area pi_calc.o area_calc.f90
\$\endgroup\$
3
\$\begingroup\$

R & C++

Requires the inline and Rcpp packages in R.

get.pi <- inline::cxxfunction(plugin="Rcpp", includes="#include <cmath>", body="return wrap(M_PI);")

get.pi() * 3 ^ 2

cxxfunction creates, compiles and links a C++ function behind the scenes. Yes, there is quite a lot of code generation happening, and return wrap(M_PI); is C++ code (along with the #include part).

\$\endgroup\$
3
\$\begingroup\$

Java + JavaScript

class Pi {
    public static void main(String... args) throws Throwable {
        System.out.println((double) new javax.script.ScriptEngineManager()
                .getEngineByName("JavaScript").eval("Math.PI")
                * Math.pow(3, 2));
    }
}
28.274333882308138
\$\endgroup\$
1
  • \$\begingroup\$ You beat me to it. :( \$\endgroup\$ Jun 16 '15 at 11:02
3
\$\begingroup\$

Julia using Python

julia> using PyCall
julia> @pyimport math
julia> math.pi*3^2
28.274333882308138

That was fun, I'd never used PyCall before. The interface is super easy to use.

\$\endgroup\$
3
\$\begingroup\$

R + grep + awk + dc

echo pi | R --no-save --quiet | grep -v '^>' | awk '{print $2}' | dc -e '?3 3 **p'

Output:

28.274337
\$\endgroup\$
3
\$\begingroup\$

Using Lua's π in Java

This program uses the library LuaJ to evaluate Lua in Java and get π. It also squares the area with Lua. Enjoy!

    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByName("luaj");
    se.eval("pi = math.pi");
    double pi = (double) se.get("pi");

    int r = 3;

    se.eval("radius = "+r);
    se.eval("rsquared = math.pow(radius, 2)");
    int rsquared = (int) se.get("rsquared");

    double area = pi * rsquared;
    System.out.println("For a circle with a diameter of "+r+", the area is "+area+".");

The output:

For a circle with a diameter of 3, the area is 28.274333882308138.

\$\endgroup\$
2
\$\begingroup\$

Jython + Java

This should work in Jython. I'm not sure, as I have no way to test it ATM.

from java.lang import Math
print Math.PI * 3 ** 2

Jython can access the Java libraries, so I can just import the Math class from java.lang and use its PI constant to calculate the area of the circle.

Golfed:

import java.lang.Math.PI;print PI*3*3

Or, if I'm allowed to code in 3^2:

import java.lang.Math.PI;print PI*9
\$\endgroup\$
2
\$\begingroup\$

bash (PI from perl,python,c)

Maybe if we combine everything we've got, we get a more accurate result? :)

#!/bin/bash
exec >&>(bc -l|tail -n1)
perl <<EOF
use Math::Trig;
print pi
EOF
echo -n +
python <<EOF
import sys
from math import pi
sys.stdout.write(str(pi))
EOF
echo -n +
cat > pi.c <<EOF
#include <math.h>
main(){printf("%.16f",M_PI);}
EOF
gcc pi.c -o pi &>/dev/null
./pi
rm -f pi pi.c
echo ";"
echo "(last/3)*3.^2"
\$\endgroup\$
2
\$\begingroup\$

Ruby+Python

puts `python -c "from math import pi; print pi"`.to_f * 3**2
\$\endgroup\$
2
\$\begingroup\$

HTML + PHP

<html><body>
value of area of circle is <br>
<?php echo 3*3*M_PI; ?>
</body></html>

Confused whether it satisfy the 3rd rule. but since M_PI is already used so it should count.

\$\endgroup\$
2
\$\begingroup\$

ACTIONSCRIPT3 + javascript(using parse.com)

Parse.CFunction('getPi',{},function(returned){trace(3*3*returned.result)});

parse class link https://github.com/camdagr8/AS3-Parse-Class/blob/master/com/illumifi/Parse.as

with code:

public static function CFunction(className:String, params:Object = null, success:Function = null, error:Function = null) {
            var url:String = Parse.api + "functions/" + className;
            Parse.Call(url, URLRequestMethod.POST, params, null, success, error);
        }

parse main.js:

Parse.Cloud.define("getPi", function(request, response) {
  response.success(Math.PI);
});

result:

28.274333882308138
\$\endgroup\$

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .