Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fa41e60

Browse files
committed
Issue #9599: Tweak loghelper algorithm to return slightly improved results for powers of 2.
1 parent d057cd6 commit fa41e60

2 files changed

Lines changed: 11 additions & 6 deletions

File tree

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2201,6 +2201,9 @@ Library
22012201
Extension Modules
22022202
-----------------
22032203

2204+
- Issue #9959: Tweak formula used for computing math.log of an integer,
2205+
making it marginally more accurate for exact powers of 2.
2206+
22042207
- Issue #9422: Fix memory leak when re-initializing a struct.Struct object.
22052208

22062209
- Issue #7900: The getgroups(2) system call on MacOSX behaves rather oddly

Modules/mathmodule.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,12 +1572,14 @@ loghelper(PyObject* arg, double (*func)(double), char *funcname)
15721572
"math domain error");
15731573
return NULL;
15741574
}
1575-
/* Special case for log(1), to make sure we get an
1576-
exact result there. */
1577-
if (e == 1 && x == 0.5)
1578-
return PyFloat_FromDouble(0.0);
1579-
/* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1580-
x = func(x) + func(2.0) * e;
1575+
/* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e.
1576+
1577+
It's slightly better to compute the log as log(2 * x) + log(2) * (e
1578+
- 1): then when 'arg' is a power of 2, 2**k say, this gives us 0.0 +
1579+
log(2) * k instead of log(0.5) + log(2)*(k+1), and so marginally
1580+
increases the chances of log(arg, 2) returning the correct result.
1581+
*/
1582+
x = func(2.0 * x) + func(2.0) * (e - 1);
15811583
return PyFloat_FromDouble(x);
15821584
}
15831585

0 commit comments

Comments
 (0)