## π Day puzzle for 3/14

63

8

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.)

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/ 2@TheDoctor Except, you didn't. – Martin Ender – 2015-03-14T20:18:48.050 38It's the 3rd day of the 14th month?? My calendar must be broken. – Gareth – 2014-03-14T17:03:57.200 You beat me to posting a Pi Day challenge :P – The Guy with The Hat – 2014-03-14T18:09:22.457 30Next year: 3/14/15 at 9:26 and 53sec, i will post a challenge – TheDoctor – 2014-03-14T22:32:27.537 5 Ugh. Tau is better. And this. – bjb568 – 2014-03-15T01:54:44.217 3@bjb I agree, Tau makes more sense, but that doesn't mean we can't have a little fun in mid march. :) – undergroundmonorail – 2014-03-15T03:40:37.080 2 – bjb568 – 2014-03-15T04:08:21.630 122/7 is a better pi day. – Ben Millwood – 2014-03-15T17:17:29.753 1I'm not sure what Pi day is, but this would have been excellent for Tau/2 day yesterday. – OJFord – 2014-03-15T21:08:27.037 9How intriguing. On π day, my reputation was 314. – tbodt – 2014-03-16T02:52:13.263 @tbodt How intriguing. On π day (and on all other days), a new user starts with a reputation of 314/314. – devnull – 2014-03-17T06:42:24.677 2http://xkcd.com/1292/ (seriously, stop this tau silliness). – Griwes – 2014-03-17T09:38:55.927 3Have anyone spotted, that this time it is not only pi day but a pi month? – V-X – 2014-03-18T07:26:59.087 I really dislike this whole "pi day" thing because it focuses on the complete wrong aspect of pi: its decimal radix form. Pi is important because it is the half period of exp(x*sqrt(-1)) WRT x, so pi day should be at the half periods of the tropical year, i.e. January 1st and July 2nd/3rd. – AJMansfield – 2014-03-18T15:38:20.800 ## Answers 129 # 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); }  67Holy crap, there's an instruction just to load the value of pi. – user2357112 supports Monica – 2014-03-15T08:05:09.457 21x86 has instructions for EVERYTHING. – fluffy – 2014-03-16T07:32:51.387 7 @user2357112 There are 7 instructions just for loading "commonly used constants" – Digital Trauma – 2014-03-16T17:20:44.993 7Good choices for the 7 constants, too! I'm always using log_e(2), but not, say, 2. – Tim S. – 2014-03-18T16:56:10.337 @TimS. My intuition tells me these FPU transistors would be better used for improving performance of say FDIV (and letting software load such constants from memory), rather than storing all these constants on the FPU. But I'm not a chip designer - what do I know :) – Digital Trauma – 2014-03-18T17:18:24.080 @TimS. log_e(2) is not equal to log(exp(2)) = 2, but actually is the natural logarithm of 2... – Mathieu Rodic – 2014-03-18T21:47:57.037 @MathieuRodic yes, but the point is that fld qword [2.0] is a 9 byte instruction, and fldln2 is a two byte instruction. The irony of @TimS.' comment is that there's plenty of constants that would have been more useful, such as -1, or 2. – primo – 2014-06-13T10:13:06.653 4@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..... – GMasucci – 2014-12-04T10:25:04.357 1@GMasucci Your mistake was trying to use the general-purpose MOV instruction on the special coffee registers. You need to use the coffee-specific instructions. – fluffy – 2014-12-04T23:39:12.157 78 ### 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. 28I just threw up a little in my mouth. – Dan Esparza – 2014-03-14T19:10:50.760 What's J and why are you running your C program with it? – NoBugs – 2014-03-16T05:41:13.383 @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. – grc – 2014-03-16T05:52:31.507 1echo$long_string > gcc -o pi? I can't believe no one caught this. Also, have you heard of here-docs|here-strings? – Blacklight Shining – 2014-03-16T21:52:54.400

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. – Kevin – 2014-03-21T15:34:44.330

41

# 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'];


4Very clever. Using a very standard way of interfacing different runtimes. =) +1 – jpmc26 – 2014-03-14T19:11:05.057

34

## 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.

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',
);

$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',
],
[
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


16

# 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. :)

4Oopsy daisy, I think I upvoted ;) – Anonymous Pi – 2014-03-14T20:11:42.467

1By 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. – undergroundmonorail – 2014-03-15T00:06:33.457

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. – Anonymous Pi – 2014-03-15T01:28:35.470

"All the code must fit in a single line". At least some people can read! – Floris – 2014-03-16T12:32:12.690

<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. – Blacklight Shining – 2014-03-16T22:00:08.030

Was going to do the same thing with Scala as it is not Java ;-) – TheConstructor – 2014-03-17T23:03:56.667

Wow. Much code. So pi. – Casey – 2014-03-18T22:21:07.860

15

## 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;
}


could've just... lua_getglobal("math");lua_getfield(-1,"pi"); – mniip – 2014-03-14T14:48:57.623

@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. – Tony Ellis – 2014-03-14T14:57:28.737

13

# bash + PHP + bc

A fairly simple one-liner:

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


Output:

28.274333882308


"All the code must fit in a single line". At least some people can read! – Floris – 2014-03-16T12:31:49.220

4@Floris: Hate to break it to you, but the question says file, not line. – Dennis – 2014-03-16T16:45:04.343

26@dennis - apparently I am not "some people"... :-/ – Floris – 2014-03-16T17:14:51.337

10

# 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

1MATLAB.. -shudders- – theGreenCabbage – 2014-03-18T20:41:45.163

@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. – MZimmerman6 – 2014-03-18T21:15:08.200

10

# 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)'


7

# perl

$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:) 6 ## 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. 5 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")) 3Looks to me more like a function in Python than a language, but it works. – None – 2014-03-14T20:05:12.110 2@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. – Juan Campa – 2014-03-15T21:21:42.130 4 # 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. 4 # 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)}'


28.274333882308


4

# VimScript + Python

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


result:

28.274334


4

# C++/C

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

int main(int argc, char** argv) {
std::cout << 3*3*M_PI << std::endl;
return 0;
}


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. – Jonathan Van Matre – 2014-03-15T12:34:25.390

4@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. – Konrad Borowski – 2014-03-15T13:29:43.757

Ah, good call there. – Jonathan Van Matre – 2014-03-15T14:12:32.797

4

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 }'"  4 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  3 # 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). 3 # 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  You beat me to it. :( – SuperJedi224 – 2015-06-16T11:02:33.477 3 # 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. 3 # R + grep + awk + dc echo pi | R --no-save --quiet | grep -v '^>' | awk '{print$2}' | dc -e '?3 3 **p'


Output:

28.274337


3

## 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;

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.

2

# 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


2

# 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"


2

## Ruby+Python

puts python -c "from math import pi; print pi".to_f * 3**2


2

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.

2

# ACTIONSCRIPT3 + javascript(using parse.com)

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


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


2

## Mathematica + R

Needs["RLink"]
InstallR[]
 = REvaluate["pi"][[1]];
R = 3;
 R^2


2

# bash + html + APL

 echo '<html><body><p>&#x25cb;3*2</p></body></html>' | w3m -dump -T text/html | apl -f -


2

Ok I'll bite...

$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!

2

## 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

system(command4)


2

"#{Math::PI*9}"


1

## ASP.net / JS

alert(3*3*<%Response.Write(Math.PI)%>)


1

# Matlab & Python

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


Output:

28.274333882308138


1

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

println java.lang.Math.PI * 3 * 3


1

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>


Umm, jQuery isn't a "language." You're using JavaScript's Math.PI from... JavaScript? – BAF – 2014-03-17T16:09:32.977

ok. edited. thanks. – Sp0T – 2014-03-18T04:15:39.083

1

## 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();
}
}
}


1

# 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;
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;
}

{
}
}

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


Output:

28.2743338823081

1

# 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


Python and Java? Please specify the language in your title as #Language# – None – 2014-03-17T22:51:46.123

0

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
`