There is a challenge for multiplying two numbers so I guess this counts too

Given as input a positive real number n compute its natural logarithm.

Your answer should be within \$10^{-6}\$ for \$1 \leq n \leq 10\$ and within \$10^{-3}\$ for \$0.1 \leq n \leq 100\$. You don't need to handle numbers outside this range.

See this thread on mathematics.se for various approaches to this problem. Just for inspiration, feel free to use a method not on that page.

Please add builtin answers to the community wiki instead of posting them separately.

Test Cases

x ln(x)
0.1 -2.3025850929940455
0.25 -1.3862943611198906
0.5 -0.6931471805599453
0.75 -0.2876820724517809
0.9 -0.10536051565782628
1.0 0.0
1.3 0.26236426446749106
2 0.6931471805599453
2.718281828459045 1.0
3.141592653589793 1.1447298858494002
4 1.3862943611198906
5 1.6094379124341003
7 1.9459101490553132
10 2.302585092994046
53 3.970291913552122
54.59815003314423 4.0
99 4.59511985013459


Standard IO rules apply. Importantly, you may take input as a fraction if you prefer. You may also output as a fraction, which does not need to be fully reduced.

  • \$\begingroup\$ Can I take input in fixed-point? (i.e. \$\lfloor n \cdot 21474836\rfloor\$) \$\endgroup\$ Commented Jul 12, 2023 at 13:52
  • \$\begingroup\$ @CommandMaster That would be acceptable \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 13:53
  • \$\begingroup\$ Would an APL answer of *⍣¯1 or a BQN answer of ⋆⁼ count as a non-builtin solution? Both say "the inverse of the function e^x", which is the natural logarithm \$\endgroup\$
    – RubenVerg
    Commented Jul 12, 2023 at 20:59
  • \$\begingroup\$ @RubenVerg There are no hard rules here, put in in whichever category you feel is most appropriate \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 21:01
  • 1
    \$\begingroup\$ @EdwinPratt That's just the definition of ln(x) so yes \$\endgroup\$
    – mousetail
    Commented Jul 13, 2023 at 9:38

19 Answers 19


Excel, 19 16 bytes

With many thanks to Dominic van Essen for the 3-byte save:




Input in cell A1. The choice of 1E9 (i.e. 1000000000) is sufficient for the given test cases and required accuracy.

  • 1
    \$\begingroup\$ Lovely! Save 1 byte by using 1e9 and 1e-9 to remove a set of parentheses... \$\endgroup\$ Commented Jul 12, 2023 at 15:16
  • 1
    \$\begingroup\$ Would 9^9*(A1^9^-9-1) work? \$\endgroup\$
    – loopy walt
    Commented Jul 12, 2023 at 16:14
  • 1
    \$\begingroup\$ @JosWoolley - It's the code that counts. If Excel auto-embellishes it later, that's not the golfer's problem... (and could even work to their advantage...) \$\endgroup\$ Commented Jul 12, 2023 at 18:23
  • 1
    \$\begingroup\$ Mathematically, it should work. I don't have Excel, so I can't pinpoint what's going wrong here. \$\endgroup\$
    – loopy walt
    Commented Jul 12, 2023 at 18:35
  • 1
    \$\begingroup\$ @loopywalt Order of operations, A1^9^-9 != A1^(9^-9) == A1^(1/9^9) \$\endgroup\$ Commented Jul 12, 2023 at 19:43


These answers are in alphabetical order based on programming language.
If your answer is identical to an existing one, please combine them.

05AB1E, 4 bytes


Try it online!

APL (Dyalog Unicode), 1 byte

Try it online!

Brachylog, 2 bytes


Try it online!

C (gcc) / PARI/GP / Julia polyglot, 3 bytes


Try it online in C (gcc)!
Attempt this online in PARI/GP!
Try it online in Julia!

CJam, 4 bytes


Try it online!

Desmos, 2 Bytes


Try it online!

Excel, 7 bytes


Go, 17 bytes


Attempt This Online!

J, 2 bytes


Attempt This Online!

J-uby, 9 bytes


Attempt This Online!

Java, 9 bytes


Try it online!

JavaScript (Node.js), 8 bytes


Try it online!

Jelly, 2 bytes


Try it online!

Julia 1.0, 3 bytes


Try it online!

MATL, 2 bytes


Try it online!

MATLAB / Octave, 4 bytes


Try it online!

Pascal, ≥ 5 bytes

The built‑in function ln fulfills the task. Its only parameter needs to be positive. Extended Pascal, ISO standard 10206, allows complex numbers, too.

ln(n)         { where `n` is an acceptable numerical expression}

Pyth, 2 bytes


Try it online!

Python 3, 20 bytes

import math

Try it online!


(log z)

Try it online!

Rust, 7 bytes


Attempt This Online!

Swift, 40 bytes

import Darwin;var l={i->Float in log(i)}


Thunno 2, 2 bytes


Try it online!

Vyxal, 2 Bytes


Try it online!

Wolfram Language (Mathematica), 3 bytes


Try it online!

  • 9
    \$\begingroup\$ Can you guys stop overwriting previous edits.. Make sure to click the refresh button before submitting your edit.. -_- \$\endgroup\$ Commented Jul 12, 2023 at 14:15

><> (Fish), 71 bytes

Trying to solve this in ><> was the original inspiration for this challenge. Posting this now instead of waiting the usual 24 hours to hopefully inspire more esolang submissions.


Hover over any symbol to see what it does

Try it

Based on the power series \$\ln(z)=2\sum_{n=0}^\infty\,\frac{1}{2n+1}\left(\frac{z-1}{z+1}\right)^{2n+1}\$ from this answer om math.se. ><> lacks exponentiation so that too must be done with a loop.

enter image description here

The green loop is the big sum while the grey loop raises to the power of 2n+1


Hexagony, 161 122 bytes


Try it online!

Layed out:

       ? . { 1 0 ' '
      2 \ } { } u 4 4
     . \ 4 4 7 6 ' * 0
    & } = . . $ / : " -
   + { = & = { { / . | "
  = } { { & = { * = { & 1
 d 0 0 0 0 0 0 } { { } 2 4
  0 5 0 4 " - ~ { & 1 3 7
   { : _ 1 & ' : ! @ . .
    ~ < > " . ) { { { =
     $ / _ " ' \ > { =
      { < > ( < \ & 1
       = / . . . . .

My first go at a Hexagony program. Could probably still be golfed some, but I'm happy to have gotten it to side length 7.

Since there are no floats in Hexagony, input and output are both fixed point \$\lfloor n\cdot10^7\rfloor\$.

The algorithm

(skip to the second paragraph if you don't care how I came up with it or why it works)

The algorithm used to approximate here is one I came up with myself. I'm sure something like it has been done before, but I'll go over how the constraints of Hexagony led me to this particular method. The first useful observation is that all logarithms are the same, at least up to a constant multiple. That is, \$\log_a(x)=\frac{\log_b(x)}{\log_b(a)}\$. This is nice because \$\log_{10}\$ is easier to work with when dealing with decimal representations. In fact, it's super easy. We can approxiamte the base ten logarithm just by taking the length of the decimal representation! Unfortunately, on the range \$[0.1, 100]\$ this give us 4 possible output values. Not quite good enough. We need a way to make our numbers longer, but longer in a very specific way. Firstly, as I mentioned earlier, we can't even enter \$0.1\$ into Hexagony, so we pad the lengths and get some necessary input precision by multiplying everything by \$10^7\$. Then, we use another simple logarithm observation: \$\log(x)=\frac{1}{n}\log(x^n)\$. Which is to say, up to another constant multiple (which was already necessary), we can take our input to any power before taking the logarithm. Great, so we just take the input to some super high power, take the length of the result and multiply it by something. But there's still a problem. While this idea technically works, it means that we'd be multiplying and measuring the length of numbers millions of digits long. I'd never be able to verify any test cases. We've successfully made our numbers longer, now we need to make them shorter. So we break the large exponent into steps, and at each step we truncate the input. By looking at how much we truncate each time we can give an approximation for how long we think it would have gotten if it didn't truncate. This approxiamtion becomes our logarithm. So, for the actual algorihtm:

We take the input and keep a running count of how many digits long we think it is. We enter a loop. For each iteration, we square the input and double this running count (since squaring roughly doubles length). We then truncate the input to the first 7 digits, and add the number of digits we took off to our running count. Iterating 24 times gives us more than enough precision. We then take our predicted length, add a constant, multiply by a constant and print it out.

The agony

So how is this implemented exactly? I'll refer to the memory graph as it is labeled below. as well as the colored paths.

colored paths for reference memory after computing ln(2)

Note that I only use one instruction pointer for this program, which is probably not optimal. We begin on the blue path. This initializes some variables, putting the input in A, 10 in H, 100000000 in I, and 24 on L leaving the memory pointer in L. Then on to the main loop in green. The main loop first uses G and F to square A, then similarly uses E and K to double D. Moving the memory pointer to B, we then use the yellow path to redirect into a sub loop on the orange tiles. This sub loop uses B an C to divide A by 10, compare against I and increment D. Once the input is less than I, We use the red path to traverse back to the main loop, putting the memory pointer back on L and decrementing. L serves as the main loop counter. Once L is 0, we break out of the main loop and on to the purple track. The purple track uses C and J to do the final subtraction and multiplication on the output in D. The final output ends up in J

Visualizations done with hexagony.net.

  • \$\begingroup\$ What approximation formula does this use? \$\endgroup\$
    – mousetail
    Commented Jul 13, 2023 at 4:31
  • 1
    \$\begingroup\$ @mousetail I added an explanation, hopefully it is clear. It kind of boggles my mind that this method works and is accurate. \$\endgroup\$ Commented Jul 13, 2023 at 15:17

Dyalog APL (no builtin), 13 12 bytes

Dyalog does have the builtin , but this way it's more fun :)


Basically just Newton's method:

$$ x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} $$

where (L is the number we are taking the log of)

$$ f(x) = e^x - L \\ f'(x) = e^x \\ x_{n+1} = x_n - \frac{e^{x_n} - L}{e^{x_n}} = x_n - 1 - \frac L {e^{x_n}} $$

           ⍨ ⍝ ‎⁡x_0 is L
         ⍣=   ⍝ ‎⁢repeat Newton's method until x_n and x_n+1 are "equal":
 ⊢-1-         ⍝ ‎⁣x_n - 1 -
     ÷∘*      ⍝ ‎⁤L / e^x_n

💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

"Equal" here means

$$ \left|x_n-x_{n+1}\right|\leq10^{-14}\max\left(\left|x_n\right|, \left|x_{n+1}\right|\right) $$

test cases

x ln(x) builtin ln(x) steps until convergence
0.1 -2.3025850929940455E0 -2.3025850929940455 8
0.25 -1.3862943611198906E0 -1.3862943611198906 7
0.5 -6.9314718055994520E-1 -0.6931471805599453 7
0.75 -2.8768207245178090E-1 -0.2876820724517809 7
0.9 -1.0536051565782634E-1 -0.10536051565782628 7
1 1.1102230246251565E-16 0 8
1.3 2.6236426446749117E-1 0.26236426446749106 7
2 6.9314718055994530E-1 0.6931471805599453 7
2.718281828459045 9.9999999999999990E-1 1 8
3.141592653589793 1.1447298858494002E0 1.1447298858494002 8
4 1.3862943611198906E0 1.3862943611198906 9
5 1.6094379124341003E0 1.6094379124341003 9
7 1.9459101490553135E0 1.9459101490553132 11
10 2.3025850929940460E0 2.302585092994046 14
53 3.9702919135521220E0 3.970291913552122 55
54.59815003314423 4 4 57
99 4.5951198501345900E0 4.59511985013459 100

gotta say, ln(1) resulting in 1e-16 is kinda annoying but well within the spec

This is 1 byte less than an implementation of Jos Woolley's, 1e9ׯ1+*∘1e¯9, but probably still has some room to be golfed further.

  • \$\begingroup\$ Great to see a new formula not seen before \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 17:55
  • \$\begingroup\$ @mousetail 10^9(x^(10^-9) - 1) is cool but newton's method is always good :)) \$\endgroup\$
    – RubenVerg
    Commented Jul 12, 2023 at 17:58

R, 18 bytes


Attempt This Online!

Port of Jos Woolley's Excel answer, using a constant of 1e9 to avoid needing parentheses to express its reciprocal of 1e-9.


Minecraft Data Pack via Lectern, 1144 bytes

@function a:a
summon bat ~ ~ ~ {Attributes:[{Name:generic.armor}]}
data merge storage  {a:[[9.,-0.9,-0.69,-0.45,-0.26,-0.14,-0.073,-0.038,-0.02,-0.011,-0.0056,-0.0029,-0.0015,-7.6e-4,-3.9e-4,-2.e-4,-1.1e-4,-5.6e-5,-2.9e-5,-1.5e-5,-7.6e-6,-3.9e-6,-2.e-6,-1.1e-6,-5.6e-7],[-1073741824,1073741824,546146222,278783439,140411372,70331752,35347866,18065629,9420929,5157943,2618732,1354293,700005,354538,181900,93273,51298,26115,13523,6995,3544,1819,933,513,261]],Operation:2,UUID:[I;0,0,0,1]}
execute as @e[type=bat] run function a:b
@function a:b
data modify entity @s Attributes[].Base set from storage  i
data modify storage  Amount set from storage  a[0][0]
data modify entity @s Attributes[].Modifiers append from storage :
execute store result score  a run attribute @s generic.armor get
execute if score  a matches 1..29 store result entity @s Attributes[].Modifiers[-1].UUID[] int 1 store result score v a run data get storage  a[1][0]
attribute @s generic.armor modifier remove 0-0-0-0-1
execute if score  a matches 1..29 run scoreboard players operation o a += v a
data remove storage  a[][0]
execute if data storage  a[][] run function a:b

The function is a:a.

Takes input in data storage : i, as a double.

Outputs via a scoreboard o a, scaled up by 466320149.

If we cannot assume a clean world with no bats, it's +8 to start with a kill @e command. If we mustn't kill the player it's another +10 for [type=bat]. If we cannot assume the objective a already exists it's +34 for scoreboard objectives add a dummy. If we can't assume the value o doesn't exist yet it's +29 for scoreboard players set o a 0.

Using a variant of binary search, we go over the values in a, multiply our value by 1+x using attributes, and if it's 1 or more we keep the multiplication and add the log of 1/(1+x) to our answer. Because the log decreases by less than half in each step we get the correct answer.

We start with a multiplication by 10 to deal with the case of \$0.1\leq x<1\$. We only perform the multiplication if the result is less than 30, to prevent the value going over 100. We need to use 30 because generic.armor is clamped to it.

Uses the fact that the storage name in Minecraft can be empty, as can the score holder. The scoreboard objective could've been as well, but then scoreboard players operation o a += v a wouldn't work because spaces are trimmed at the end of each line.


Jelly, 8 bytes


Try it online!

Uses the formula \$\ln(z) \approx 10^9(z^{10^{-9}} - 1)\$, adapted slightly from Jos Woolley's answer

How it works

*İ}’×ʋȷ9 - Main link. Takes z on the left
      ȷ9 - 10^9
     ʋ   - Last 4 links as a dyad f(z, 10^9):
  }      -   To 10^9:
 İ       -     Take it's reciprocal
*        -   Raise z to the power 10^-9
   ’     -   Decrement
    ×    -   Multiple by 10^9

Jelly, 14 bytes


Try it online!

Uses the series definition $$\ln(z) = 2\sum^\infty_{n = 0} \frac 1 {2n+1} \left(\frac {z-1} {z+1}\right)^{2n+1}$$

For this series, \$1000\$ is more than enough to provide the required accuracy, as pointed out by mousetail for -1 byte!

How it works

’÷‘*÷ṛɗȷŻḤ‘¤SḤ - Main link. Takes z on the left
’              - z-1
  ‘            - z+1
 ÷             - (z-1)/(z+1)
           ¤   - Last links as a nilad:
       ȷ       -   10^4
        Ż      -   [0, 1, 2, ..., 1000]
         Ḥ     -   [0, 2, 4, ..., 2000]
          ‘    -   [1, 3, 5, ..., 2001]
      ɗ         - Last 3 links as a dyad f((z-1)/(z+1), [1, 3, 5, ..., 2001]):
   *            -   [(z-1)/(z+1), (z-1)/(z+1)^3, (z-1)/(z+1)^5, ...]
    ÷ṛ          -   [(z-1)/(z+1), ((z-1)/(z+1)^3)/3, ((z-1)/(z+1)^5)/5, ...]
             S  - Sum
              Ḥ - Unhalve; Double
  • \$\begingroup\$ Even just taking 16 iterations gives the required accuracy, so replacing ȷ4 with ³ should save a byte \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 17:22
  • 1
    \$\begingroup\$ @mousetail ³ becomes the first command line argument when one is provided. However, ȷ by itself defaults to 1000, so I can save the byte that way instead. Thanks! \$\endgroup\$ Commented Jul 12, 2023 at 18:05

Python 3, 24 bytes

lambda x:1e9*(x**1e-9-1)

Try it online!

Port of Jos Woolley's Excel answer (and Dominic van Essen's R answer).

Somehow only 4 bytes off the built-in.


Ruby, 20 bytes

CW because it's literally a copy-and-paste of The Thonnu's Python 3 answer.


Attempt This Online!


Charcoal, 12 bytes


Try it online! Link is to verbose version of code. Explanation: Port of @JosWooley's Excel answer.

       N        Input number
      X         Raised to power
         χ      Predefined variable `10`
        X       Raised to power
           χ    Predefined variable `10`
          ±     Negated
     ⊖          Decremented
 ×              Multiplied by
   χ            Predefined variable `10`
  X             Raised to power
    χ           Predefined variable `10`
I               Cast to string
                Implicitly print

Importing math.log from Python costs 11 bytes:


Try it online! Link is to verbose version of code.


Python, 84 bytes

def f(x):
 while i:g=i+x*(i*i/g-(i:=i-1))
 return x*s/g

Attempt This Online!

Thanks @xnor for -1.


Evaluates a continued fraction https://en.wikipedia.org/wiki/Euler%27s_continued_fraction_formula

  • 1
    \$\begingroup\$ 1-2*(x>1) -> 1|-(x>1) \$\endgroup\$
    – xnor
    Commented Jul 12, 2023 at 23:16
  • \$\begingroup\$ Thanks, @xnor. This should be generally useful! \$\endgroup\$
    – loopy walt
    Commented Jul 12, 2023 at 23:18

Python, 85 Bytes

f=lambda x:sum(1/y for y in range(9**7,round(x*9**7)+1))if x>1else-f(1/x)if x-1else 0
  • Thanks to TheThonnu for their 86 byte suggestion, probably borrowing the 9**7 idea from Command Master.
  • Thanks to c-- for showing it is 1 byte shorter to not have a k variable.

Uses numerical integration.

Try It Online! (I've used the Pypy implementation in the TIO website since it's apparently 4x faster)

  • \$\begingroup\$ You can remove the spaces before the ifs and elses to save 4 bytes, maybe more \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 14:39
  • \$\begingroup\$ if x!=1 can be if x-1 for -1 byte \$\endgroup\$
    – mousetail
    Commented Jul 12, 2023 at 14:40
  • \$\begingroup\$ 1000000 can be 9**7 for -3 \$\endgroup\$ Commented Jul 12, 2023 at 14:52
  • \$\begingroup\$ 86 bytes \$\endgroup\$
    – The Thonnu
    Commented Jul 12, 2023 at 16:05
  • 2
    \$\begingroup\$ @Iamkindofalanguagedev 1e6 won't work since range requires integers. \$\endgroup\$
    – The Thonnu
    Commented Jul 12, 2023 at 16:27

JavaScript (Node.js), 18 bytes


Try it online!

Port of Excel answer


C (gcc), 44 bytes

float f(float x){return(pow(x,1e-9)-1)*1e9;}

Try it online!

Port of Jos Woolley's Excel answer


BQN, 2 bytes

 ⁼  # ‎⁡The inverse of
⋆   # ‎⁢the function e^x

💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

yeah ok this might be cheating :) can mark as community wiki or delete and move to the builtin answer if enough people complain


Swift 5.6, no imports, 146 bytes

Swift has no log or pow builtins -- you have to import those from C! Here's a Swift answer that doesn't use any imports:

let i:(Float,Int)->_={x,y in(0..<y).reduce(1){n,_ in n*x}}
func l(x:Float)->Float{2*(0...126).reduce(0){$0+i((x-1)/(x+1),2*$1+1)/(.init($1)*2+1)}}

SwiftFiddle link with test cases. Uses this method from the linked Math.SE post. 126 is just the magic number needed to get the requisite precision for \$\ln\left(99\right)\$.

This works in later versions of Swift, but I'm pinning it to 5.6 in case exponentiation is added in the future. i is a handwritten exponentiation function where the exponent must be a positive integer (called Int instead of UInt to save bytes).


Python, 130 bytes

def f(x):
 x,m=(1/x,-1)if x<1 else(x,1)
 while x>1.03:x,m=x**.5,m<<1
 return m*90*(x-1)/(7*x+32*((x+1)*r+2*x)**.5+12*r+7)

This algorithm is derived from Carlson's version of Borchard's algorithm, which uses a modified arithmetic-geometric mean. Carlson's version adds Richardson acceleration. See Carlson, B. C. “An Algorithm for Computing Logarithms and Arctangents.” Mathematics of Computation, Apr 1972 https://doi.org/10.2307/2005182

My version is essentially two loops of Carlson's, with range reduction. It only uses elementary operations and square roots. Its absolute error is under 5e-14. Here are some error plots: error plot, 0.1 - 1 error plot 1 - 100

Try it in SageMathCell


Itr, 12 bytes


online interpreter

check all test-cases


Uses Newtons method starting at 0 to approximate the result.

$x            ; store the input in x
  '¿F         ; repeat 191 times (enough for all test-cases)
     äeäx-\-  ; replace top stack value y starting at 0 with
              ; y-(e^y-x)/e^y (step in Newton method)
              ; implicitly print result

Itr, 17 bytes


Also works for negative (and complex) inputs

x>3*i sets the initial value to 3i if the real part of the input is negative


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.