Shorten an already short mathematical expression

15

2

For once, I was doing some real work, updating old code, and bumped into an expression that is equivalent to what would be written as πx + ex in good old-fashioned math. I thought it would be possible to write it shorter than it was written in the language I work with (APL), and therefore present this very simple challenge:

Write a function or program that (by any means) accepts zero or more numbers, and returns (by any means) the result of the above expression for x = each of the given numbers with at least 3 significant digits for each result.

If your language does not have π and/or e, use the values 3.142 and 2.718.

Scoring is number of bytes, so preface your answer with # LanguageName, 00 bytes.

Standard loop-holes are not allowed.


Edit: Now the solution I came up with, ○+*, has been found. The original code was (○x)+*x.

Adám

Posted 2015-12-21T18:25:15.810

Reputation: 37 779

5What domain are the inputs drawn from? Integers, reals, complex numbers? – Martin Ender – 2015-12-21T18:36:14.770

1@MartinBüttner Whatever you like, as long as the output isn't restricted to integer. – Adám – 2015-12-21T18:41:07.983

Answers

21

Dyalog APL, 3 characters

As a tacit phrase.

○+*

Monadic multiplies its argument with π, monadic * is the exponential function exp. ○+* is a train such that (○+*)ω is equal to (○ω)+(*ω). Since this is APL, the phrase works for arguments of arbitrary shape, e. g. you can pass a vector of arbitrary length.

The same solution is possible in J as o.+^ with o. being and ^ being *.

FUZxxl

Posted 2015-12-21T18:25:15.810

Reputation: 9 656

:-) See "Edit:" in OP. – Adám – 2015-12-21T19:36:36.880

So, I down voted you by mistake and only just realized. Mind making some minor edit so I can change that? – ankh-morpork – 2015-12-24T16:11:39.673

@dohaqatar7 Like this? – FUZxxl – 2015-12-24T16:43:20.930

30

Emotinomicon, 48 bytes / 13 characters

I do it, not because it is short, but because it is fun. Try it here. You'll have to copy+paste it into the textbox.

⏪✖➕⏩

Explanation:

  ⏪       ✖       ➕         ⏩   explanation
                                              take numeric input
    ⏪                                           open loop
                                              duplicate top of stack
                                              push pi
                ✖                               multiply top two elements on stack
                                              reverse stack
                                              pop N, push e^N
                            ➕                   add top two elements on stack
                                              take numeric input
                                              duplicate top of stack
                                              pop N, push N+1
                                            ⏩   close loop

Here is the program in its native environment, the mobile phone: the image

Conor O'Brien

Posted 2015-12-21T18:25:15.810

Reputation: 36 228

1Definitely the most entertaining expression. – Adám – 2015-12-21T19:38:08.040

7Lol, a cat for cat? – geokavel – 2015-12-21T19:44:30.987

3I want this language. – Faraz Masroor – 2015-12-22T04:07:50.143

2I suppose you could say he use sub-expressions. (•_•) ( •_•)>⌐■-■ (⌐■_■) – Addison Crump – 2016-02-20T00:09:31.263

9

R, 25 24 bytes

cat(exp(x<-scan())+pi*x)    

Is this it? It gets input from user, assign it to x, calculates its exponential multiply it to pi, and finally cat()prints the result.

edit: 1 bytes saved thanks to Alex A.

Mutador

Posted 2015-12-21T18:25:15.810

Reputation: 1 361

1Looks right to me. – Adám – 2015-12-21T18:42:06.000

224 bytes: cat(exp(x<-scan())+pi*x) – Alex A. – 2015-12-21T23:43:58.693

In this case you have to use <- as I did in my suggestion rather than = because otherwise it's setting the x argument for exp but not assigning the variable x. In a fresh session the current code will fail. – Alex A. – 2015-12-23T16:53:35.797

7

JavaScript (ES6), 39 34 bytes

Saved 5 bytes thanks to @edc65

a=>a.map(x=>x*Math.PI+Math.exp(x))

Takes input as an array of numbers, and outputs in the same format.

Thanks to the reduction, there are now three equivalent 45-byte programs, all ES5-compliant:

for(;x=prompt();)alert(x*Math.PI+Math.exp(x))
for(M=Math;x=prompt();)alert(x*M.PI+M.exp(x))
with(Math)for(;x=prompt();)alert(x*PI+exp(x))

Inputs should be entered one at a time. Press OK without entering anything to quit.

The third one highlights an interesting feature in JS: the with statement. While sometimes unsafe to use (thus disabled in strict mode), it can still be used to save typing out an object name and period every time you need to access it. For example, you can do this:

x=[];with(x)for(i=0;i<5;i++)push(length);

push and length are then used as properties of x, which will result with x being [0,1,2,3,4].

This works on any object, even non-variables, so for example, you can do this:

with("0123456789ABCDEF")for(i=0;i<length;i++)alert("0x"+charAt(i)-0);

charAt and length are called as properties of the string. "0x"+x-0 converts x from a hex value to a number, so this alerts the numbers 0 through 15.

ETHproductions

Posted 2015-12-21T18:25:15.810

Reputation: 47 880

1M.pow(M.E,x) is M.exp(x) by definition – edc65 – 2015-12-21T21:54:48.957

@edc65 I should learn my Math ;) Thanks! – ETHproductions – 2015-12-21T22:38:40.770

I didn't know with was deprecated. – Conor O'Brien – 2015-12-23T00:57:23.413

@CᴏɴᴏʀO'Bʀɪᴇɴ My bad; it's not deprecated, but avoiding it is highly suggested.

– ETHproductions – 2015-12-23T01:51:28.017

That's what I remember reading. ^_^ I use it anyways in <canvas> rendering and (of course) golfing. – Conor O'Brien – 2015-12-23T01:52:38.090

6

Pyth, 11 13

VQ+*N.n0^.n1N

Now takes x as a list, e.g. [1.25, 2.38, 25]

Previous (11 bytes): +*Q.n0^.n1Q

VQ            +       * N .n0            ^ .n1 N
For each      Add     List Item * Pi     e ^ List Item
input item

Moose

Posted 2015-12-21T18:25:15.810

Reputation: 883

When I try this with the online interpreter, it only works for a single number. Or what is the input format? The specification says that the input is "zero or more numbers", and the expression has to be evaluated for "each of the given numbers." – Reto Koradi – 2015-12-21T18:47:58.533

@RetoKoradi you can run it with multiple numbers (on separate lines) by checking the "switch to test suite" box. I'm not sure if that's allowed now that you mention it. – Moose – 2015-12-21T18:51:23.600

6

Mathematica, 11 10 bytes

N@Pi#+E^#&

With 1 byte saved thanks to LegionMammal978.

DavidC

Posted 2015-12-21T18:25:15.810

Reputation: 24 524

This currently does not work. However, for 10 bytes: 1.Pi#+E^#& – LegionMammal978 – 2015-12-22T13:23:14.273

There was a space missing between # and Pi. This is solved by using Pi# in place of #Pi. Also, N only needs to be applied to Pi#, not the whole expression. – DavidC – 2015-12-22T15:17:33.190

5

Seriously, 10 bytes

,`;e(╦*+`M

Hex Dump:

2c603b6528cb2a2b604d

Try It Online

Takes inputs as a list (see link for example).

Explanation:

,                               Get input list
 `      `M                      Map this function over it
  ;                             Copy the input value.
   e                            exponentiate
    (                           dig up the other copy
     ╦*                         multiply by pi
       +                        add

quintopia

Posted 2015-12-21T18:25:15.810

Reputation: 3 899

5

Python 2, 38 bytes (52 49 bytes w. math)

lambda l:[3.142*x+2.718**x for x in l]

If I have to use the math module:

from math import*
lambda l:[pi*x+e**x for x in l]

Input should be a list of numbers

f([1,2,3,4,5])

> [5.8599999999999994, 13.671524, 29.505290232, 67.143510850576007, 164.04623849186558]

TFeld

Posted 2015-12-21T18:25:15.810

Reputation: 19 246

2If your language does not have π and/or e, use the values 3.142 and 2.718. ... Python has pi and e in the math module. – Zach Gates – 2015-12-21T22:33:33.223

@ZachGates Added a version with math module. – TFeld – 2015-12-22T17:38:18.310

You can save 3 bytes on the math solution by using from math import* – wnnmaw – 2015-12-22T21:37:27.253

@wnnmaw Thanks! – TFeld – 2015-12-22T21:51:02.887

You can also shave off another by using for x in l:lambda l:pi*x+e**x instead of the comprehension in both answers – wnnmaw – 2015-12-22T21:54:08.207

5

MATLAB, 15 bytes

@(x)pi*x+exp(x)

costrom

Posted 2015-12-21T18:25:15.810

Reputation: 478

5

TI-BASIC, 5 bytes

πAns+e^(Ans

TI-BASIC doesn't use ASCII bytes, so each of these is stored as one byte in the calculator: π, Ans, +, e^(, and Ans. It assumes the previous expression is the input (like {1,2,3}).

NinjaBearMonkey

Posted 2015-12-21T18:25:15.810

Reputation: 9 925

4

MATL, 9 bytes

This answer uses the current version of the language (3.1.0), which is earlier than the challenge.

itYP*wZe+

Input is a vector containing all numbers (list enclosed by square brackets and separated by spaces, commas of semicolons), such as [5.3 -7 3+2j]. Complex values are allowed. Output has 15 significant digits.

Example

>> matl itYP*wZe+
> [1 2 3]
5.859874482048839 13.67224140611024 29.51031488395705

Explanation

Straightforward operations:

i       % input  
t       % duplicate 
YP      % pi   
*       % multiplication
w       % swap elements in stack                           
Ze      % exponential                                      
+       % addition 

Luis Mendo

Posted 2015-12-21T18:25:15.810

Reputation: 87 464

4

MATLAB: 70 bytes

@(x)num2str(arrayfun(@(x)(round(pi*x+exp(x),2-floor(log10(pi*x+exp(x))))),x))

Test:

ans(1:10)
5.86            13.7            29.5            67.2             164             422            1120            3010            8130           22100

Explanation: There were several issues with number formatting.

Firstly, the question requires 3 sig-figs. Matlab has no built-in function for rounding by sig-figs (only by decimal places), so the following workaround was required:

floor(log10(pi*x+exp(x)))) computes the largest significant digit.

@(x)(round(pi*x+exp(x),2-floor(log10(pi*x+exp(x))))),x)) takes input x and rounds to 3 significant digits.

Another requirement was to handle multiple inputs. The above code can work only with single number. To mitigate this, we use arrayfun to evaluate the function for each vector element.

The last problem, Matlab displays the result of arrayfun with its own rounding that leads to outputs like 1.0e+04 * 0.0006 which violates the 3 sig-fig requirement. So, num2str was used to turn array into char format.

Matlab is good for numerical analysis, but, frankly, it sucks when it comes to fine number formatting

UPD: well, that's embarrassing that I confused

with at least 3 significant digits

with

with 3 significant digits

Anyway, I'll leave my answer in this form because the 15 bytes Matlab solution is already given by @costrom

brainkz

Posted 2015-12-21T18:25:15.810

Reputation: 349

2What?! Why do you have to do all that? – Adám – 2015-12-21T19:39:18.033

4Is this code-bowling? – Stewie Griffin – 2015-12-21T19:46:30.730

I'll add explanations for the answer – brainkz – 2015-12-21T19:49:00.433

1it only says a minimum of 3 sig figs, not exactly 3. if you specified that format longg was required before running the code, you'd drop 3/4 the length here – costrom – 2015-12-21T20:08:33.973

@costrom Yes, you're right, and I concede that you win :) – brainkz – 2015-12-21T20:11:56.420

Found the numerical analyst. – Soham Chowdhury – 2015-12-23T14:24:12.957

4

Julia, 12 bytes

x->π*x+e.^x

This is an anonymous function that accepts an array and returns an array of floats. To call it, give it a name, e.g. f=x->....

Julia has built-in constants π and e for—you guessed it—π and e, respectively. The .^ operator is vectorized exponentiation.

Alex A.

Posted 2015-12-21T18:25:15.810

Reputation: 23 761

3

Haskell, 22 19 bytes

map(\x->pi*x+exp x)

Try it online!

Edit: -3 bytes thanks to @H.PWiz

nimi

Posted 2015-12-21T18:25:15.810

Reputation: 34 639

3

Japt, 12 bytes

N®*M.P+M.EpZ

Takes input as space-separated numbers. Try it online!

How it works

N®   *M.P+M.EpZ
NmZ{Z*M.P+M.EpZ

        // Implicit: N = array of inputs, M = Math object
NmZ{    // Map each item Z in N to:
Z*M.P+  //  Z times PI, plus
M.EpZ   //  E to the power of Z.
        // Implicit: output last expression

ETHproductions

Posted 2015-12-21T18:25:15.810

Reputation: 47 880

I hated to upvote you when you're at 5,554 rep. – Conor O'Brien – 2015-12-21T20:07:07.473

3

J, 4 bytes

o.+^

Same as APL ○+*, but J's pi times function is called o., which is one byte longer.

Lynn

Posted 2015-12-21T18:25:15.810

Reputation: 55 648

2

Par, 8 bytes

✶[″℗↔π*+

Accepts input as (1 2 3)

Explanation

               ## [implicit: read line]
✶              ## Parse input as array of numbers
[              ## Map
 ″             ## Duplicate
 ℗             ## e to the power
 ↔             ## Swap
 π*            ## Multiply by π
 +             ## Add

Ypnypn

Posted 2015-12-21T18:25:15.810

Reputation: 10 485

2

CJam, 13 bytes

q~{_P*\me+}%p

Takes input as an array separated by spaces (e.g. [1 2 3]). Try it online.

Explanation

q~    e# Read the input and evaluate it as an array
{     e# Do this for each number x in the array...
  _P* e# Multiply x by pi
  \me e# Take the exponential of x (same as e^x)
  +   e# Add the two results together
}%
p     e# Pretty print the final array with spaces

NinjaBearMonkey

Posted 2015-12-21T18:25:15.810

Reputation: 9 925

@NBZ Done, thanks for clarifying. – NinjaBearMonkey – 2015-12-23T15:56:31.663

2

Racket, 27 bytes

map(λ(x)(+(* pi x)(exp x)))

when put in the function position of an expression:

(map(λ(x)(+(* pi x)(exp x))) '(1 2 3 4))

> '(5.859874482048838 13.672241406110237 29.510314883957047 67.16452064750341)

Matthew Butterick

Posted 2015-12-21T18:25:15.810

Reputation: 401

1

Reng v.3.3, 53 bytes

Noncompeting because it postdates the challenge, but hey, not winning any awards for brevity. :P Try it here!

2²5³*:"G"(%3+i#II*ZA*9+(%2+#E1II0e1+ø
1-)E*(:0eø
$+n~

Line 0

Here is a view of the stack in line 0:

Sequence read | Stack
2²            | 4
5³            | 4 125
*             | 500
:             | 500 500
"G"           | 500 500 71
(             | 500 71 500
%             | 500 0.142
3+            | 500 3.142
i             | 500 3.142 <i>
#I            | 500 3.142     ; I <- i
I             | 500 3.142 <i>
*             | 500 3.142*<i>
ZA            | 500 3.142*<i> 35 10
*             | 500 3.142*<i> 350
9+            | 500 3.142*<i> 359
(             | 3.142*<i> 359 500
%             | 3.142*<i> 0.718
2+            | 3.142*<i> 2.718
#E            | 3.142*<i>     ; E <- 2.718
1II0          | 3.142*<i> 1 <i> <i> 0
e             | 3.142*<i> 1 <i> <i>==0
1+            | 3.142*<i> 1 <i> (<i>==0)+1

ø then goes to the next Nth line. When 0 is input, this goes straight to line 2. Otherwise, we go to line 1.

Line 1

1-)E*(:0eø

This multiples E i times, which is e^i. We decrement the counter (initially I), multiply the STOS (our running e power) by E, go back to the counter, and do this (i' is the current counter):

Sequence read | Stack (partial)
              | i'
:             | i' i'
0             | i' i' 0
e             | i' i'==0

ø then does one of two things. If the counter is not 0, then we go to the "next" 0th line, i.e., the beginning of the current line. If it is zero, then 0e yields 1, and goes to the next line.

Line 2

$+n~

$ drops the counter (ON THE FLOOR!). + adds the top two results, n outputs that number, and ~ quits the program.

Case 1: input is 0. The TOS is 1 ("e^0") and the STOS is 0 (pi*0). Adding them yields the correct result.

Case 2: input is not 0. The result is as you might expect.

Conor O'Brien

Posted 2015-12-21T18:25:15.810

Reputation: 36 228