Função inversa


31

Não seria legal se as funções de programação pudessem ser invertidas, assim como a função matemática que elas implementam?

Escreva uma função (ou programa) que receba uma entrada xde qualquer forma, que saia ln(x).
Quando os bytes do programa são reordenados / revertidos para que o primeiro byte agora seja o último, ele deve receber uma entrada xem qualquer formato e saída e^x.

  • Sua resposta deve ter pelo menos três valores significativos corretos.
  • As aproximações são boas, desde que tenham pelo menos três valores significativos corretos.
  • Seu código deve estar na mesma linguagem de programação para frente e para trás.

Digamos que este programa implemente ln(x):

abc你好

Então este programa precisa implementar e^x:

\xBD\xA5\xE5\xA0\xBD\xE4cba

Estrela de ouro se você usar um idioma sem suporte de flutuação.

Essa é uma forma estranha de código-golfe, então o programa mais curto vence.


4
"Não seria legal se as funções de programação pudessem ser invertidas, assim como a função matemática que elas implementam?" Alguns idiomas (por exemplo, J e Mathematica) podem realmente fazer isso para algumas funções.
— Martin Ender

Além disso, K2 poderia aproximar um inverso para uma função pura monádica arbitrária por meio de sua sobrecarga "função inversa" de diádica e triádica ?, que usava o método secante.
— Johne

1
"pelo menos 3 valores significativos corretos" - em que faixa?
— TLW 06/02

4
Sei que agora é tarde demais, mas acho que esse seria um desafio muito bom se os comentários não fossem permitidos.
— Alex A.

Na verdade, pensei nisso quando me deparei com esse desafio @AlexA. mas esqueci enquanto escrevia o post: P Também isso tornaria linguagens "normais" como java, c ++ etc. basicamente impossíveis.
— Filip Haglund

Respostas:


75

Haskell, 11 bytes

f=log
pxe=f

e na ordem inversa:

f=exp
gol=f

Isso funciona sem o truque "comentar". Em vez disso, cada versão define uma função adicional, mas não utilizada ( pxe/ gol).


49
+1 para gol=f.
— Leif Willerts

2
Essa também é uma solução válida em Julia.
— Rainer P.

44

APL, 3 bytes

*⊣⍟

Este é um trem funcional. Monádicas * retornos e^x, monádicas ⍟retornos ln(x). ⊣é uma função diádica que retorna seu argumento esquerdo. Assim, *⊣⍟é equivalente a apenas *, e o inverso ⍟⊣*é equivalente a apenas ⍟.


22

Geléia, 5 4 bytes

Sim, minha primeira resposta Jelly. :) A entrada é via argumento da linha de comando.

O Jelly tem sua própria página de código, portanto, cada caractere tem um byte.

eÆÆl

Experimente online!

Invertida:

lÆÆe

Experimente online!

Explicação

Por Æsi só, é um token não reconhecido e, portanto, age da mesma forma que um avanço de linha. Isso significa que, em ambos os casos, o link principal é apenas Ælou Æequal é o caractere de 2 caracteres incorporado exp()ou ln()é executado por padrão no primeiro argumento da linha de comando.


9

Javascript, 18 bytes

Math.log//pxe.htaM

Você não precisa de um return () ou console.log ()?
— OldBunny2800

2
@OldBunny2800 It evaluates to a function, which should be permissible.
— Neil

5
Math.ln||pxe.htaM will probably also work.
— SuperJedi224

@SuperJedi224 Thanks, that helped me spot the error in my answer!
— Neil

@Neil I hadn't even noticed that
— SuperJedi224

7

Seriously, 5 bytes

,_.e,

Input, ln, output, then exp on an empty stack (does nothing), and input (does nothing since input is exhausted). Try it online!

Reversed:

,e._,

Try it online!


5

Julia, 7 bytes

log#pxe

This is an anonymous function. Assign it to a variable to call it. Evaluates to builtins log or exp plus a comment.


1
Same answer works for R
— Dason

5

Mathematica, 19 bytes

1&#@pxE+0&0+Log@#&1

Reversed:

1&#@goL+0&0+Exp@#&1

This was interesting to golf! Mathematica has no line comments / implicit string endings, so I couldn't take the simple route. Instead, I used the fact that 0 + x == x, 0 x == 0, and that 1 x == x, no matter what x is! Testing:

In[1]:= (1&#@pxE+0&0+Log@#&1)[x]

Out[1]= Log[x]

In[2]:= (1&#@goL+0&0+Exp@#&1)[x]

         x
Out[2]= E

4

Python2, 73 bytes

io: stdin/stdout

from math import*;print log(input())#))(tupni(pxe tnirp;*tropmi htam morf

inverse:

from math import*;print exp(input())#))(tupni(gol tnirp;*tropmi htam morf

You can shave 10 characters off by using __import__("math"). instead of
— TLW

3

CJam, 11 bytes

rdmle#eemdr

Test it here.

Reversed:

rdmee#elmdr

Test it here.

Basically the same comment-trick as the OP's Python answer. e# starts a comment. rd reads the input and ml or me computes the logarithm or exponential.


3

Brachylog, 3 bytes

*₁≡

Try it online!

Initially, I had hoped to use ~*, but although *~ computes e^x and successfully ignores the trailing tilde, ~* fails for all integer inputs and hits a float overflow on most non-integer inputs.

Forwards:

       The output
  ≡    is
*₁     the natural logarithm of
       the input.

Backwards:

       The output is
  *    Euler's number to the power of
       the input
≡      passed through the identity predicate
 ₁     with an extraneous subscript.

This uses the identity predicate because, although trailing tildes are tolerated, leading subscripts are not. (If they were, the Brachylog answer would be *₁ alone, which is just the normal builtin for natural log.)


2

Vitsy, 5 bytes

This is a program that exits on an error.

EL^rE
E   E  Push java.lang.Math.E
 L     Push log_(top) (input) (ln(input))
  ^    Push (top)^(input)  (e^(input))
   r   Reverse the stack

This program exits on an error with ln(input) on the stack.

Try it online! (note that I have put N to have visible output)

Then it's inverse:

Er^LE

This program exits on an error with e^(input) on the stack.

Try it online!


2

Fuzzy Octo Guacamole, 7 bytes

non-competing, FOG is newer than the challenge

EZO@pZE

This is the equivalent of a function in FOG. It assumes the input is on the stack. This can be assigned to a function by the code "EZO@pZE""f"o, where f is any single-char name you want to assign. Then use it like any other command. Example: "EZO@pZE"'f'o^f.

Explanation:

EZO@pZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # log(x, y) which is ln(input)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # x^y (power function)
     Z  # Reverse stack
      E # Push E.

Reversed:

EZp@OZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # x^y (power function)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # log(x, y) which is ln(input)
     Z  # Reverse stack
      E # Push E.


1

Pyth, 12 bytes

Finds ln(input())

.lQ) " Q1n.^

Finds e^input()

^.n1Q " )Ql.

Spaces stop implicit printing of strings, each version calculates it then creates a string with the remaining characters.

ln(x) mode here

e^x mode here



1

Jolf, 9 bytes

Program 1: exp of input

amoj"jOma
a         print
 moj      e^j
    "jOma  the rest of the line is captured as a string; implicit printing is restricted.

Program 2: ln of input

amOj"joma
a         print
 mOj      ln(j)
    "joma  the rest of the line is captured as a string; implicit printing is restricted.

Bonus points for being a case-insensitive palindrome? Try it here!


1

J, 8 bytes

The natural logarithm is ^., and exponential ^. The problem is, . can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase ^.[^ would cause an error when reversed, as ^[.^ creates an invalid verb. So, we must use comments; but NB. is so long :( Fortunately, they both end with ., so&ldots; there's that.

Logarithm:

^.NB.BN^

Exponential:

^NB.BN.^

You can enter them for yourself online!



0

Runic Enchantments, 9 bytes

i'lA@Ae'i

Try it online!

An ungodly uninteresting program. @ insures termination of the implied entry point at the left, everything after is unexecuted. I tried really hard to re-use the ' or A instructions, but to no avail, even at larger program sizes. The required explicit entry point for multi-line programs essentially precludes it.

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.