Persingkat ekspresi matematika yang sudah pendek


15

Untuk sekali, saya melakukan beberapa kerja nyata, memperbarui kode lama, dan menabrak sebuah ekspresi yang setara dengan apa yang akan ditulis sebagai πx + e x dalam matematika kuno yang baik. Saya pikir mungkin untuk menulisnya lebih pendek daripada yang ditulis dalam bahasa tempat saya bekerja (APL), dan karenanya menyajikan tantangan yang sangat sederhana ini:

Tulis fungsi atau program yang (dengan cara apa pun) menerima angka nol atau lebih, dan mengembalikan (dengan cara apa pun) hasil dari ekspresi di atas untuk x = masing-masing angka yang diberikan dengan setidaknya 3 digit signifikan untuk setiap hasil.

Jika bahasa Anda tidak memiliki π dan / atau e , gunakan nilai 3.142 dan 2.718.

Skor adalah jumlah byte, jadi kata pengantar jawaban Anda dengan # LanguageName, 00 bytes.

Lubang loop standar tidak diperbolehkan.


Sunting: Sekarang solusi yang saya temukan○+* ,, telah ditemukan . Kode aslinya adalah (○x)+*x.


5
Dari domain apa input diambil? Bilangan bulat, real, bilangan kompleks?
Martin Ender

1
@ MartinBüttner Apa pun yang Anda suka, selama output tidak terbatas pada integer.
Adám

Jawaban:


21

Dyalog APL, 3 karakter

Sebagai frasa diam-diam.

○+*

Monadic mengalikan argumennya dengan π, monadik *adalah fungsi eksponensial exp. ○+*adalah kereta yang (○+*)ωsama dengan (○ω)+(*ω). Karena ini adalah APL, frasa ini berfungsi untuk argumen yang bentuknya sewenang-wenang, e. g. Anda dapat melewati vektor dengan panjang sewenang-wenang.

Solusi yang sama dimungkinkan dalam J seperti o.+^dengan o.makhluk dan ^makhluk *.


:-) Lihat "Edit:" di OP.
Adám

Jadi, saya memilih Anda secara tidak sengaja dan baru sadar. Pikiran membuat beberapa perubahan kecil sehingga saya bisa mengubahnya?
ankh-morpork

@ dohaqatar7 Anda suka ini?
FUZxxl

30

Emotinomicon, 48 byte / 13 karakter

Saya melakukannya, bukan karena itu pendek, tetapi karena itu menyenangkan. Coba di sini. Anda harus menyalin + menempelkannya ke kotak teks.

😼⏪🆙😦✖😎😿➕😨😼🆙😄⏩

Penjelasan:

😼  ⏪   🆙  😦  ✖   😎  😿  ➕   😼  🆙  😄  ⏩   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

Berikut adalah program di lingkungan asalnya, ponsel: the image


1
Ekspresi yang paling menghibur.
Adám

7
Lol, untuk kucing cat?
geokavel

3
Saya ingin bahasa ini.
Faraz Masroor

2
Saya kira Anda bisa mengatakan dia menggunakan sub ekspresi . (• _ •) (• _ •)> ⌐ ■ - ■ (⌐ ■ _ ■)
Addison Crump

9

R, 25 24 byte

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

Apakah ini? Ia mendapat input dari pengguna, menetapkannya x, menghitung eksponensialnya, mengalikannya pi, dan akhirnya cat()mencetak hasilnya.

sunting: 1 byte disimpan berkat Alex A.


1
Terlihat benar bagiku.
Adám

2
24 byte:cat(exp(x<-scan())+pi*x)
Alex A.

Dalam hal ini Anda harus menggunakan <-seperti yang saya lakukan dalam saran saya daripada =karena kalau tidak itu menetapkan xargumen untuk exptetapi tidak menetapkan variabel x. Dalam sesi baru, kode saat ini akan gagal.
Alex A.

7

JavaScript (ES6), 39 34 byte

Disimpan 5 byte berkat @ edc65

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

Mengambil input sebagai array angka, dan output dalam format yang sama.

Berkat pengurangan ini, sekarang ada tiga program 45 byte yang setara, semua sesuai dengan ES5:

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

Input harus dimasukkan satu per satu. Tekan OK tanpa memasukkan apa pun untuk berhenti.

Yang ketiga menyoroti fitur menarik di JS: withpernyataan. Meskipun kadang-kadang tidak aman untuk digunakan (sehingga dinonaktifkan dalam mode ketat), masih dapat digunakan untuk menyimpan mengetikkan nama objek dan titik setiap kali Anda perlu mengaksesnya. Misalnya, Anda dapat melakukan ini:

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

pushdan lengthkemudian digunakan sebagai properti dari x, yang akan menghasilkan xmakhluk [0,1,2,3,4].

Ini berfungsi pada objek apa pun , bahkan non-variabel, jadi misalnya, Anda bisa melakukan ini:

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

charAtdan lengthdisebut sebagai properti dari string. "0x"+x-0mengkonversi xdari nilai hex ke angka, jadi ini alertadalah angka 0 hingga 15.


1
M.pow(M.E,x)adalah M.exp(x)menurut definisi
edc65

@ edc65 Saya harus belajar Math;) Terima kasih!
ETHproduk

Saya tidak tahu withsudah ditinggalkan.
Conor O'Brien

@ CᴏɴᴏʀO'Bʀɪᴇɴ Buruk saya; itu tidak ditinggalkan, tetapi menghindarinya sangat disarankan .
ETHproduksi

That's what I remember reading. ^_^ I use it anyways in <canvas> rendering and (of course) golfing.
Conor O'Brien

6

Mathematica, 11 10 bytes

N@Pi#+E^#&

With 1 byte saved thanks to LegionMammal978.


This currently does not work. However, for 10 bytes: 1.Pi#+E^#&
LegionMammal978

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

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

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

@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

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


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


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]

2
If 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

@ZachGates Added a version with math module.
TFeld

You can save 3 bytes on the math solution by using from math import*
wnnmaw

@wnnmaw Thanks!
TFeld

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

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 

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


2
What?! Why do you have to do all that?
Adám

4
Is this code-bowling?
Stewie Griffin

I'll add explanations for the answer
brainkz

1
it 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

@costrom Yes, you're right, and I concede that you win :)
brainkz

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.


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

I hated to upvote you when you're at 5,554 rep.
Conor O'Brien

3

J, 4 bytes

o.+^

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



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

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)

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

@NBZ Done, thanks for clarifying.
NinjaBearMonkey

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.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.