gh-154146: Fix accuracy of the math.acospi() fallback near 1 (GH-154148)

serhiy-storchaka <[email protected]>
Newsgroups gmane.comp.python.cvs
Message-ID <[email protected]>
https://github.com/python/cpython/commit/69f080144972d1dd0acd445d776cdaea788923ed
commit: 69f080144972d1dd0acd445d776cdaea788923ed
branch: main
author: Serhiy Storchaka <[email protected]>
committer: serhiy-storchaka <[email protected]>
date: 2026-07-20T08:56:50+03:00
summary:

gh-154146: Fix accuracy of the math.acospi() fallback near 1 (GH-154148)

Co-authored-by: Claude Fable 5 <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-07-19-19-05-00.gh-issue-154146.acospi.rst
M Modules/mathmodule.c

diff --git a/Misc/NEWS.d/next/Library/2026-07-19-19-05-00.gh-issue-154146.acospi.rst b/Misc/NEWS.d/next/Library/2026-07-19-19-05-00.gh-issue-154146.acospi.rst
new file mode 100644
index 00000000000000..5dbddbadee0bd3
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-19-19-05-00.gh-issue-154146.acospi.rst
@@ -0,0 +1,2 @@
+Fix accuracy of :func:`math.acospi` for arguments close to 1
+on platforms that do not provide ``acospi()`` in libm.
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c
index 64e5372d73d2f2..eaa1850b8aee1a 100644
--- a/Modules/mathmodule.c
+++ b/Modules/mathmodule.c
@@ -220,6 +220,12 @@ static const double logpi = 1.144729885849400174143427351353058711647;
 static double
 m_acospi(double x)
 {
+    if (x >= 0.5) {
+        /* acos(x) = 2*asin(sqrt((1 - x)/2)).  1 - x is exact here.
+           Some libms (old fdlibm derivatives) lose precision in acos(x)
+           near x = 1, while asin() is accurate for small arguments. */
+        return 2.0*asin(sqrt((1.0 - x)/2.0))/pi;
+    }
     double r = acos(x)/pi;
     if (isgreater(r, 1.0)) {
         return 1.0;

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.