g | x | w | all
Bytes Lang Time Link
085Perl 5 a241121T201251ZXcali
154Haskell241121T024438ZMaroonSp
092JavaScript Node.js230505T000139ZnaffetS
087Factor221220T114256Zchunes
112JavaScript Node.js221218T113615Zl4m2
104AWK221218T101616Zcnamejj
106JavaScript221218T091139ZAlexande
02905AB1E legacy180801T130055ZKevin Cr
153C150729T035222ZJerry Je
172PHP190831T065754Zmickmack
118Runic Enchantments190610T225011ZDraco18s
112Javascript190607T124845Zruler23
095Perl 5.10+190103T004217Zdolmen
196Dart181206T090041ZElcan
175Kotlin181206T060653Zsnail_
096R180801T154031ZJayCe
143Mathetmatica160624T155006ZLLlAMnYP
119Python 3130421T141101Zflornqua
243Java160128T001732ZJack Amm
159Perl120109T012616ZCatherin
119JavaScript ES7150728T201343ZDowngoat
265C++150919T205415ZZereges
070K5150730T231140Zkirbyfan
229C150730T143941ZCole Cam
228Matlab150729T113643ZLuis Men
147MATLAB –150729T104439ZAmro
002Python130419T152445Zflornqua
205Python 2.7140916T184923ZMB6
241C#111221T152243Zkev
132Python 3110505T183929Zcemper93
131ECMAScript 6140916T191329ZIngo B&#
130Python131020T083450ZDaniel L
206Python131019T081357Zgolfer93
157flex130420T042058ZGeoff Re
155Haskell110505T000027Zmarinus
nan110506T033546Zuser unk
nan110921T154138ZSam Tobi
392C#110205T142848ZMiffTheF
128Perl110204T002127ZJ B
077Ruby110130T070547ZNemo157
240PHP110130T031836ZKevin Br
162Scheme110130T030614ZC. K. Yo
259PHP110130T172543ZAurel B&
124Python110130T114328Zgnibbler
161Python110130T115544ZThomas O
152Windows PowerShell110130T100640ZJoey
424c 424 necessary character110130T061234Zdmckee -
166Python110130T053654ZKeith Ra
134Perl110130T051121ZMing-Tan
157JavaScript110130T031146Zuser11

Perl 5 -a, 85 bytes

push@;,/\d/?$_:do{$s=pop@;;$f=pop@;;/\+/?$f+$s:/\*/?$f*$s:/\//?$f/$s:$f-$s}for@F;say@

Try it online!

Haskell (154)

data P n=N n|O(n->n->n)
p"+"=O(+)
p"-"=O(-)
p"*"=O(*)
p"/"=O(/)
p n=N$read n
l!N n=n:l
(x:y:l)!O f=f y x:l
main=interact$show.head.foldl(!)[0].map p.words

Try it online!

Note: this is based on someone else's code (here), which I found posted on Reddit (here). I just made it shorter.

JavaScript (Node.js), 92 bytes

s=>(g=(d,c=q.pop())=>1/c?+c:(b=g(d=g()),c)>'-'?b/d:c>'+'?b-d:c>'*'?b+d:b*d)(q=s.split(/ +/))

Try it online!

Factor, 87 bytes

[ " "split [ dup dec> [ dec> ] [ last "+-*/"index { + - * / } nth execute ] if ] each ]

Try it online!

Or, if word lookup (i.e. converting a string to an executable function of the same name) doesn't count as too eval-y:

Factor, 72 bytes

[ " "split [ dup dec> [ dec> ] [ "math"lookup-word execute ] if ] each ]

Try it online!

JavaScript (Node.js), 112 bytes

s=>s.split` `.map(i=>1/i?i&&t.push(+i):t.push([(r=t.pop())+(o=t.pop()),o-r,r*o,o/r]['+-*/'.indexOf(i)]),t=[])&&t

Try it online!

Modified from an existing answer but did thorough modify :(

AWK, 104 bytes

{for(;i++<NF;d[e]=b?--b?--b?--b?f/g:f*g:f-g:f+g:$i)(b=index("+-*/",$i))?(g=d[e--])(f=d[e]):e++}1,$0=d[e]

Try it online!

This one mostly abuses ternaries like a case statement to save characters... The code loops through each conditional argument, setting variable b to 0-5 depending on whether the argument is a number (b==0) or an index 1-4 into the string "+-*/". Then the "end of loop" code uses b to either compute the results of a mathematical operation, or just to reference the current argument.

It uses array d like a stack.

for(;i++<NF;                                     ) - loops through args
            d[e]=b?--b?--b?--b?f/g:f*g:f-g:f+g:$i  - effectively a "case" statement

And the body of the loop does:

(b=index("+-*/",$i))?                  :    - sets "b" to 0-5, also if/then/else
                     (g=d[e--])(f=d[e])     - set "f" and "g" to args to be used in math
                                        e++ - for numbers, advance stack pointer

And once all the argument have been processed:

1,$0=d[e] - the "1," forces output even if "d[e]" is 0

JavaScript, 106

e=i=>i.split(' ').reduce((s,t)=>[s,isNaN(t)?eval([s.pop(),s.pop()].reverse().join(t+' ')):t].flat(),[])[0]

Testing code

console.log([
    '-4 5 +',
    '5 2 /',
    '5 2.5 /',
    '5 1 2 + 4 * 3 - +',
    '4 2 5 * + 1 3 2 * + /'
].map(e))

Output

[1, 2.5, 2, 14, 2]

UPD I've just noticed that eval is not allowed, but it's not the only JS solution with eval so I'd let it posted

05AB1E (legacy), 32 30 29 bytes

#vyDd≠i©'+Qi+ë®'-Qi-ë®'*Qi*ë/

Try it online or verify all test cases.

Explanation:

#                # Split the (implicit) input-string on spaces
 vy              # Loop `y` over each item:
   D             #  Duplicate `y` so it's now twice on the stack
    d≠i          #  If it's NOT a number:
       ©         #   Store the operator-character in variable `®` (without popping)
        '+Qi    '#   If it's a "+":
            +    #    Add the top two numbers together
       ë®'-Qi   '#   Else-if it's a "-":
             -   #    Subtract the top two numbers from each other
       ë®'*Qi   '#   Else-if it's a "*":
             *   #    Multiply the top two numbers together
       ë         #   Else (it's a "/"):
        /        #    Divide the top two numbers
                 # (after the loop: implicitly output the result)

We're using the legacy version, because d checks if a value is a number, whereas the new 05AB1E version would check if it's a non-negative number (\$\geq0\$) instead.


If eval would have been allowed, it's 14 11 bytes instead:

9LD(s'(«:.V

Try it online or verify all test cases.

Explanation:

9L           # Push the list [1,2,3,4,5,6,7,8,9]
  D          # Duplicate it on the stack
   (         # Negate each integer: [-1,-2,-3,-4,-5,-6,-7,-8,-9]
    s        # Swap to get the original list again
     '(«    '# Append a "(" to each: ["1(","2(","3(","4(","5(","6(","7(","8(","9("]
        :    # Replace all "-N" with "N(" in the (implicit) input-string
         .V  # Eval the string as 05AB1E code
             # (implicitly output the result)

Negative numbers are indicated with a trailing ( instead of leading - in 05AB1E. Apart from that, the calculations are also done in Reverse Polish Notation style.

C 153

Sometimes a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else.

Thanks to @ceilingcat for finding a much better (and shorter) version

double atof(),s[99],*p=s;y,z;main(c,v)char**v;{for(;--c;*p=z?z-2?~z?z-4?p+=2,atof(*v):*p/y:*p*y:*p-y:*p+y)z=1[*++v]?9:**v-43,y=*p--;printf("%f\n",s[1]);}

Try it online!

My original version:

#include <stdlib.h>
#define O(x):--d;s[d]=s[d]x s[d+1];break;
float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);}

If you are compiling it with mingw32 you need to turn off globbing (see https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html) by compiling like this:

gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o

If you don't * is automatically expanded by the mingw32 CRT into filenames.

PHP, 172 bytes (Demo)

<?foreach(preg_split('~ +~',fgets(STDIN))as$v)if(floatval($v))$s[]=$v;else{[$e,$d]=array_splice($s,-2);$s[]=$v=="+"?$e+$d:($v=="-"?$e-$d:($v=="*"?$e*$d:$e/$d));}echo $s[0];

Previously entertained techniques:

<?do{$_GET[a]=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$_GET[a],1,$c);}while($c);echo $_GET[a]; // 208

<?$v=$_GET[a];do{$v=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$v,1,$c);}while($c);echo $v; // 202

<?while(preg_match('~(.*?)(-?[\d.]+) (-?[\d.]+) ([*/+-])(.*)~',$_GET[a],$m))$_GET[a]=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $_GET[a]; // 198

<?$v=$_GET[a];while(preg_match('~(.*?)(-?[\d.]+) +(-?[\d.]+) +([*/+-])(.*)~',$v,$m))$v=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $v;  // 194

Runic Enchantments, 118 bytes

?!/rRlril1-{=
R:0q}"+0"{:}≠?\"-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\R}l1=?!@
\r\ /<?6+{{~{~/?7-S{{~{~/?8 *{{~{~/?7,S{{~/\

Try it online!

Runic already operates in Reverse Polish Notation, so its just a matter of reading the input and converting from char-based symbols to actual operators.

Due to the near-perfect space usage on the lower line, ≠?\ works out to the same number of bytes as =?!\, but is easier to read.

Explanation

    /<                                                Entry
?!\rRlril1-{=                                         Read all inputs
/r/                                                   Reverse the stack (we need to parse from front to back, not back to front; mirrors flipped to preserve visual flow direction within the explanation)
R                                                     Initial parsing loop entry
 :                                                    Duplicate
  0q}                                                 Concat TOS with a 0 on the end
     "+0"                                             Construct string +0 (checking for addition)
         {:}                                          RoL, Dup, RoR (this allows the same i0 string concatenation to be reused)
            ≠?\                                       Compare, if not equal, continue
               "-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\           Do the same for -, *, and /
                                           R          Bottom-of-loop entry
                                            }         Rotate numerical value to bottom of stack
                                             l1=?!@   If stack is only 1 object, print and terminate
           ~{~/                                       If equal, pop no-longer-needed i0 concatenations and the original input char
        +{{                                           Add most recent 2 values
      ?6                                              Skip to bottom-of-loop
               ?7-S{{~{~/?8 *{{~{~/?7,S{{~/           Similar chunks for -, *, and /
                                           \          Mirror up to bottom of main loop (after-math skips wind up here)
                                     ,S{{~            Note that division does not need to pop no-longer-needed concatenated string, as we used up the last one in the comparison

Invalid input characters will be treated as their decimal equivalents because chars implicitly convert to ints. Strings will crash.

Operators must be compared with their string equivalents, again, because chars implicitly convert to ints. A numerical 43 is identical to the character +. 0q is the shortest method of generating a unique string representation of the stack object that can be compared with known expected strings. Additionally a string may not be the ToS when constructing a new string or the two strings are automatically concatenated.

Javascript, 112 bytes

r=c=>(s=[],f=(a,b,o)=>eval(`${b}${o}${a}`),c.split(' ').forEach(e=>s.push(!+e?f(s.pop(),s.pop(),e):+e)),s.pop())

Zero error checking, uses the eval function, but it works with all valid RPN expressions.

r is a function (eg. r('2 3 +') returns 4)

Perl 5.10+: 95 bytes

perl '-anEmy@a;push@a,/\d/?$_:do{$j=pop@a;$i=pop@a;($i*$j,$i+$j,0,$i-$j,0,$i/$j)[-42+ord]}for@F;say$a[0]'

Size 95 bytes (diff with perl -e '' which is 10 bytes).

Ungolfed, expanding command line flags (thanks to perl -MO=Deparse '-anE...) and slightly edited:

use feature 'say';
while (defined($_ = readline)) {
    our @F = split(' ', $_, 0);
    my @a;
    push @a, /\d/ ? $_ : do {
        $j = pop @a;
        $i = pop @a;
        ($i * $j, $i + $j, 0, $i - $j, 0, $i / $j)[-42 + ord($_)]
    } foreach (@F);
    say $a[0];
}

Notes:

An alternate implementation using regexp matching and replacement: 100 bytes

perl '-pEwhile(s!\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])!" ".($1*$2,$1+$2,0,$1-$2,0,$1/$2)[-42+ord$3]!e){}y/ //d'

Ungolfed:

use feature 'say';

while (defined($_ = readline ARGV)) {
    while (s[\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])][' ' . ($1 * $2, $1 + $2, 0, $1 - $2, 0, $1 / $2)[-42 + ord($3)];]e) {
        ();
    }
    y/ //d;
} continue {
    die "-p destination: $!\n" unless print $_;
}

Dart, 196 bytes

F(l,n)=>l.removeAt(l.length-1-n);G(a,b,c)=>c=='+'?a+b:c=='-'?a-b:c=='*'?a*b:a/b;f(s){var l=[];s.split(' ').forEach((a){l.add('+-*/'.contains(a)?G(F(l,1),F(l,0),a):double.parse(a));});return l[0];}

Try it online!

Kotlin, 175 bytes

{var s=List(0){0f}
for(t in it.split(" ")){try{s=s+t.toFloat()}catch(e:Exception){val(a,b)=s.takeLast(2)
s=s.dropLast(2)+listOf(a+b,a-b,a*b,a/b)["+-*/".indexOf(t)]}}
s.last()}

Try it online!

R, 132 105 96 bytes

for(i in scan(,""))F="if"(grepl("[0-9]",i),c(as.double(i),F),c(get(i)(F[2],F[1]),F[-1:-2]));F[1]

Try it online!

Port of Amro's Matlab answer. I never realized the two languages had so much in common. Saved 27 bytes thanks to Giuseppe ! See edit history for test cases.

Mathetmatica, 143 bytes

Last@Flatten[#~ImportString~"CSV"&/@StringSplit@#]//.{{a___,b_,c_,o_String,d___}:>{a,o[b,c],d},"+"->Plus,"*"->Times,"/"->Divide,"-"->Subtract}&

Anonymous function, takes a string as input (StringSplit[#]), splits at whitespace, ImportString[#,"CSV"] acts on each element separately (it's like a soft form of eval), converting number-like strings to numbers, however operators remain as strings.

//. - repeatedly apply replacement rule: go through the input list, until you hit an operator character, e.g. {1, 4, 2, / *} becomes {1 /[4,2] *}, then {*[1, /[4,2]]}.

String-forms of operators are replaced with the names of the actual Mathematica functions which do the required thing. Output is a number.

Python 3, 119 bytes

s=[]
for x in input().split():
 try:s+=float(x),
 except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2],
print(s[0])

Input: 5 1 1 - -7 0 * + - 2 /

Output: 2.5

(You can find a 128-character Python 2 version in the edit history.)

Java 243

Input comes from the command line. Element 0 in the Float[ ] isn't actually used for storing the inputs, however it is needed for the first assignment of the temp value. The Float constructor takes care of parsing for negative values and values with a decimal place.

interface R{static void main(String[]a){Float t,f[]=new Float[a.length];int i=0;for(String s:a){t=f[i];switch(s){case"-":t=-t;case"+":f[--i]+=t;break;case"/":t=1/t;case"*":f[--i]*=t;break;default:f[++i]=new Float(s);}}System.out.print(f[i]);}}

Ungolfed:

interface ReversePolishNotation{
    static void main(String[]arg){
        Float temp, fVals[]=new Float[arg.length];
        int i=0;
        for(String str:arg){
            temp=fVals[i];
            switch(str){
                case"-":
                    temp=-temp;
                case"+":
                    fVals[--i]+=temp; break;
                case"/":
                    temp=1/temp;
                case"*":
                    fVals[--i]*=temp; break;
                default:
                    fVals[++i]=new Float(str);
            }
        }
        System.out.print(fVals[i]);
    }
}

Perl, 159

sub c{pop@s}sub z{push@s,$_[0]}while(<>){($_,$a)=/(\S*) ?(.*)/;z$_ if/\d/;z(('-'eq$_?- c:c)+c)if/[+-]/;z(('/'eq$_?1/c:c)*c)if/[*\/]/;redo if$_=$a;print c."\n"}

And here's the ungolfed version:

#!/usr/bin/perl
 
sub c{pop @stack}
sub z{push @stack,$_[0]}
while (<>) {
    ($_, $a) = /(\S*) ?(.*)/;
    z$_ if /\d/;
    z(('-'eq$_?- c:c)+c) if /[+-]/;
    z(('/'eq$_?1/c:c)*c) if /[*\/]/;
    redo if $_=$a;
    print c . "\n"
}

Not really much to look at, but I'm pretty happy with it. I managed to at least beat the Scheme version :)

JavaScript ES7, 119 bytes

I'm getting a bug with array comprehensions so I've used .map

(s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t)

Try it online at ESFiddle

C++, 265 bytes

Worse than first thought, looking for improvements.

#include<iostream>
#include<string>
#include<stack>
#define G s.top();s.pop()
using namespace std;int main(){string t; stack<float>s;while(cin>>t)if(47<t.back()&t.back()<58)s.push(stof(t));else{float a,b=G;a=G;s.push(t=="+"?a+b:t=="-"?a-b:t=="*"?a*b:a/b);}cout<<G;}

Usage

Run -> input -> enter -> Ctrl+Z -> enter  (windows)
                      -> Ctrl+D           (unix)

Ungolfed

#include <iostream>
#include <string>
#include <stack>
#define G s.top(); s.pop()
using namespace std;

int main()
{
    string t;
    stack<float> s;
    while (cin >> t)
    {
        if (47 < t.back() & t.back() < 58)
            s.push(stof(t));
        else
        {
            float a, b = G;
            a = G;
            s.push(t=="+" ? a+b : t=="-" ? a-b : t=="*" ? a*b : a/b);
        }
    }
    cout << G;
}

K5, 70 bytes

`0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:`

I'm not sure when K5 was released, so this might not count. Still awesome!

C, 232 229 bytes

Fun with recursion.

#include <stdlib.h>
#define b *p>47|*(p+1)>47
char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));}

Ungolfed:

#include <stdlib.h>

/* Detect if next char in buffer is a number */
#define b *p > 47 | *(p+1) > 47

char*p; /* the buffer */

float a(float m)
{
    float n = strtof(p, &p); /* parse the next number */

    /* if the next thing is another number, recursively evaluate */
    b ? n = a(n) : 0;

    for(;*++p==32;); /* skip spaces */

    /* Perform the arithmetic operation */
    m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n;

    /* If there's more stuff, recursively parse that, otherwise return the current computed value */
    return *++p && b ? a(m) : m;
}

int main(int c, char **v)
{
    printf("%f\n", a(strtof(v[1], &p)));
}

Test Cases:

$ ./a.out "-4 5 +"
1.000000
$ ./a.out "5 2 /"
2.500000
$ ./a.out "5 2.5 /"
2.000000
$ ./a.out "5 1 2 + 4 * 3 - +"
14.000000
$ ./a.out "4 2 5 * + 1 3 2 * + /"
2.000000

Matlab, 228

F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1
n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end
t{1}

Ungolfed:

F = '+-/*'; %// possible operators
f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun
t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces
i = str2double(t); %// convert each split string to number
j =~ isnan(i); %// these were operators, not numbers ...
t(j) = num2cell(i(j)); %// ... so restore them
while numel(t)>1
    n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator
    t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace
    t(n-2:n-1)=[]; %// remove used numbers
end
t{1} %// display result

MATLAB – 158, 147

C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q

(input is read from user input, output printed out).


Below is the code prettified and commented, it pretty much implements the postfix algorithm described (with the assumption that expressions are valid):

C = strsplit(input('','s'));         % prompt user for input and split string by spaces
D = str2double(C);                   % convert to numbers, non-numeric are set to NaN
q = [];                              % initialize stack (array)
for i=1:numel(D)                     % for each value
    if isnan(D(i))                   % if it is an operator
        f = str2func(C{i});          % convert op to a function
        q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result
    else
        q = [D(i) q];                % else push value on stack
    end
end
q                                    % show result

Bonus:

In the code above, we assume operators are always binary (+, -, *, /). We can generalize it by using nargin(f) to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in:

f = str2func(C{i});
n = nargin(f);
args = num2cell(q(n:-1:1));
q = [f(args{:}) q(n+1:end)];

That way we can evaluate expressions like:

str = '6 5 1 2 mean_of_three 1 + 4 * +'

where mean_of_three is a user-defined function with three inputs:

function d = mean_of_three(a,b,c)
    d = (a+b+c)/3;
end

Python 2

I've tried out some different approaches to the ones published so far. None of these is quite as short as the best Python solutions, but they might still be interesting to some of you.

Using recursion, 146

def f(s):
 try:x=s.pop();r=float(x)
 except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)]
 return r,s
print f(raw_input().split())[0]

Using list manipulation, 149

s=raw_input().split()
i=0
while s[1:]:
 o='+-*/'.find(s[i])
 if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]]
 i+=1
print s[0]

Using reduce(), 145

print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0]

Python 2.7 (205 bytes)

Edit: Version 2. After consideration I was able to shave off a lot by using the operator module:

from operator import *
f={'*':mul,'/':div,'+':add,'-':sub}
def e(r):
    l=[]
    for i in r:
        try:i=float(i);l.append(i)
        except:l.append(f[i](*l[-2:]));del l[-3:-1]
    return l
print e(raw_input().split())[0]

C# - 323 284 241

class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}}

Edit: Replacing the Stack with an Array is way shorter

Edit2: Replaced the ifs with a ternary expression

Python 3, 126 132 chars

s=[2,2]
for c in input().split():
    a,b=s[:2]
    try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]]
    except:s=[float(c)]+s
print(s[0])

There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too.

ECMAScript 6 (131)

Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow:

f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop())

Python, 130 characters

Would be 124 characters if we dropped b and (which some of the Python answers are missing). And it incorporates 42!

s=[]
for x in raw_input().split():
 try:s=[float(x)]+s
 except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]]
print s[0]

Python - 206

import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop
for t in i:
 if t=="+":a(b()+b())
 elif t=="-":m=b();a(b()-m)
 elif t=="*":a(b()*b())
 elif t=="/":m=b();a(b()/m)
 else:a(float(t))
print(b())

Ungolfed version:

# RPN

import sys

input = sys.argv[1].split()
stack = []

# Eval postfix notation
for tkn in input:
    if tkn == "+":
        stack.append(stack.pop() + stack.pop())
    elif tkn == "-":
        tmp = stack.pop()
        stack.append(stack.pop() - tmp)
    elif tkn == "*":
        stack.append(stack.pop() * stack.pop())
    elif tkn == "/":
        tmp = stack.pop()
        stack.append(stack.pop()/tmp)
    else:
        stack.append(float(tkn))

print(stack.pop())

Input from command-line argument; output on standard output.

flex - 157

%{
float b[100],*s=b;
#define O(o) s--;*(s-1)=*(s-1)o*s;
%}
%%
-?[0-9.]+ *s++=strtof(yytext,0);
\+ O(+)
- O(-)
\* O(*)
\/ O(/)
\n printf("%g\n",*--s);
.
%%

If you aren't familiar, compile with flex rpn.l && gcc -lfl lex.yy.c

Haskell (155)

f#(a:b:c)=b`f`a:c
(s:_)![]=print s
s!("+":v)=(+)#s!v
s!("-":v)=(-)#s!v
s!("*":v)=(*)#s!v
s!("/":v)=(/)#s!v
s!(n:v)=(read n:s)!v
main=getLine>>=([]!).words

Scala 412 376 349 335 312:

object P extends App{
def p(t:List[String],u:List[Double]):Double={
def a=u drop 2
t match{
case Nil=>u.head
case x::y=>x match{
case"+"=>p(y,u(1)+u(0)::a)
case"-"=>p(y,u(1)-u(0)::a)
case"*"=>p(y,u(1)*u(0)::a)
case"/"=>p(y,u(1)/u(0)::a)
case d=>p(y,d.toDouble::u)}}}
println(p((readLine()split " ").toList,Nil))}

Racket 131:

(let l((s 0))(define t(read))(cond[(real? t)
(l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s)
(car s)),@(cddr s)))][0(car s)]))

Line breaks optional.

Based on Chris Jester-Young's solution for Scheme.

C# - 392 characters

namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

However, if arguments can be used instead of standard input, we can bring it down to

C# - 366 characters

namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

Perl, 128

This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path.

perl -plE '@_=split" ";$_=$_[$i],/\d||
do{($a,$b)=splice@_,$i-=2,2;$_[$i--]=
"+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_?
$a*$b:$a/$b;}while++$i<@_'

Characters counted as diff to a simple perl -e '' invocation.

Ruby - 95 77 characters

a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]

Takes input on stdin.

Testing code

[
  "-4 5 +",
  "5 2 /",
  "5 2.5 /",
  "5 1 2 + 4 * 3 - +",
  "4 2 5 * + 1 3 2 * + /",
  "12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
  puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end

gives

[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0

Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.

PHP, 439 265 263 262 244 240 characters

<? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1];

This code should work with stdin, though it is not tested with stdin.

It has been tested on all of the cases, the output (and code) for the last one is here:
http://codepad.viper-7.com/fGbnv6

Ungolfed, 314 330 326 characters

<?php
$c = fgets(STDIN);
$a = array_values(array_filter(explode(" ", $c)));
$s[] = 0;
foreach($a as $b){
    if(floatval($b)){
        $s[] = $b;
        continue;
    }
    $d = array_pop($s);
    $e = array_pop($s);
    $s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :"")));
}
echo $s[1];

Scheme, 162 chars

(Line breaks added for clarity—all are optional.)

(let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t
`((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s))
,@(cddr s)))))(else(car s)))))

Fully-formatted (ungolfed) version:

(let loop ((stack '()))
  (let ((token (read)))
    (cond ((number? token) (loop `(,token ,@stack)))
          ((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/)))
           => (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack))
                                    ,@(cddr stack)))))
          (else (car stack)))))

Selected commentary

`(,foo ,@bar) is the same as (cons foo bar) (i.e., it (effectively) returns a new list with foo prepended to bar), except it's one character shorter if you compress all the spaces out.

Thus, you can read the iteration clauses as (loop (cons token stack)) and (loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack))) if that's easier on your eyes.

`((+ ,+) (- ,-) (* ,*) (/ ,/)) creates an association list with the symbol + paired with the procedure +, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are (read) in as symbols, which is why no further processing on token is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P

† This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across.

PHP - 259 characters

$n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2];

Assuming input in POST variable i.

Python - 124 chars

s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)]
print s[0]

Python - 133 chars

s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:]
print s[0]

Python, 161 characters:

from operator import*;s=[];i=raw_input().split(' ')
q="*+-/";o=[mul,add,0,sub,0,div]
for c in i:
 if c in q:s=[o[ord(c)-42](*s[1::-1])]+s 
 else:s=[float(c)]+s
print(s[0])

Windows PowerShell, 152 181 192

In readable form, because by now it's only two lines with no chance of breaking them up:

$s=@()
switch -r(-split$input){
  '\+'        {$s[1]+=$s[0]}
  '-'         {$s[1]-=$s[0]}
  '\*'        {$s[1]*=$s[0]}
  '/'         {$s[1]/=$s[0]}
  '-?[\d.]+'  {$s=0,+$_+$s}
  '.'         {$s=$s[1..($s.count)]}}
$s

2010-01-30 11:07 (192) – First attempt.

2010-01-30 11:09 (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer.

2010-01-30 11:19 (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to float.

2010-01-30 11:19 (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char.

2010-01-30 11:39 (152) – Greatly reduced by using regex matching in the switch. Completely solves the previous scope issues with accessing the stack to pop it.

c -- 424 necessary character

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define O(X) g=o();g=o() X g;u(g);break;
char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];};
void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){
b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0:
case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*)
case'/':O(/)}}else n:u(atof(b));}}

Assumes that you have a new enough libc to include getdelim in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with strsep and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - * / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by atof which means zero value if they don't look like numbers.

Readable and commented:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *p=NULL,*b;
size_t a,n=0;
float g,s[99];
float o(){        /* pOp */
  //printf("\tpoping '%f'\n",s[n-1]);
  return s[--n];
};
void u(float v){  /* pUsh */
  //printf("\tpushing '%f'\n",v);
  s[n++]=v;
};
int main(){
  getdelim(&p,&a,EOF,stdin); /* get all the input */
  for(;;){
    b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p
                 points at the rest of the input */
    if(3>p-b){
      if (*b>='0'&&*b<='9') goto n;
      //printf("Got 1 char token '%c'\n",*b);
      switch (*b) {
      case 0:
      case EOF: printf("%f\n",o()); return 0;
      case '+': g=o(); g=o()+g; u(g); break;
      case '-': g=o(); g=o()-g; u(g); break;
      case '*': g=o(); g=o()*g; u(g); break;
      case '/': g=o(); g=o()/g; u(g); break;
    /* all other cases viciously ignored */
      } 
    } else { n:
      //printf("Got token '%s' (%f)\n",b,atof(b));
      u(atof(b));
    }
  }
}

Validation:

 $ gcc -c99 rpn_golf.c 
 $ wc rpn_golf.c
  9  34 433 rpn_golf.c
 $ echo -4 5 + | ./a.out
1.000000
 $ echo 5 2 / | ./a.out
2.500000
 $ echo 5 2.5 / | ./a.out
2.000000

Heh! Gotta quote anything with * in it...

 $ echo "5 1 2 + 4 * 3 - +" | ./a.out
14.000000
 $ echo "4 2 5 * + 1 3 2 * + /" | ./a.out
2.000000

and my own test case

 $ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out
-20.500000

Python, 166 characters

import os,operator as o
S=[]
for i in os.read(0,99).split():
 try:S=[float(i)]+S
 except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:]
print S[0]

Perl (134)

@a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s

Next time, I'm going to use the recursive regexp thing.

Ungolfed:

@a = split /\s/, <>;
for (@a) {
    /\d/
  ? (push @s, $_)
  : ( $x = pop @s,
      $y = pop @s,
      push @s , ( '+' eq $_ ? $x + $y
                : '-' eq $_ ? $y - $x
                : '*' eq $_ ? $x * $y
                : '/' eq $_ ? $y / $x
                : 0 )
      )
}
print(pop @s);

I though F# is my only dream programming language...

JavaScript (157)

This code assumes there are these two functions: readLine and print

a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0])