Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

4 of 4
change test and add table
RubenVerg
  • 1.3k
  • 6
  • 20

Dyalog APL (no builtin), (削除) 13 (削除ここまで) 12 bytes

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

(⊢-1-÷∘*)⍣=⍨

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}} $$

(⊢-1-÷∘*)⍣=⍨
 ⍨ ⍝ ‎⁡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, 1e×ばつ ̄1+*∘1e ̄9, but probably still has some room to be golfed further.

RubenVerg
  • 1.3k
  • 6
  • 20

AltStyle によって変換されたページ (->オリジナル) /