Le samedi 24 février 2024 à 18:11:25 UTC+1, Gareth Ma a écrit :

Note that you can wrap it in `Decimal` or `Fraction`, which are both 
builtin Python libraries.

I stand corrected. Python ints are bignums, *not* 32-bits integers. and 
fractions.Fractions are rationals. Ordinary integer arithmetic wroks with 
these rationals. We just need a binomial coefficient function returning an 
int (math.comb returns a float) :
>>> from math import factorial >>> from fractions import Fraction >>> def 
ibin(n, k): return Fraction(factorial(n), factorial(k)*factorial(n-k)) if 
n>=k else 0 ... >>> def g(n, k, r): return 
(-1)**k*ibin(n,k)*Fraction((n-k)**r, n**r) ... >>> def f(n, r): return 
float(sum([g(n,k,r) for k in range(n+1)])) ... >>> f(365, 2000) 
0.21611945163321844 

A tad more muscular than using Sage…

Thanks a lot ! I learned something useful today…

On Saturday 24 February 2024 at 13:54:51 UTC Emmanuel Charpentier wrote:

Le vendredi 23 février 2024 à 23:23:20 UTC+1, Dima Pasechnik a écrit :

[ Snip…]

the normal Python way, without any symbolic sum, would be like this:


sage: sage: g(n,k,r)=(-1)^(k)*binomial(n,k)*(n-k)^r/n^r
....: sage: def f(n,r): return math.fsum([1.0*g(n,k,r) for k in range(n+1)])
....: sage: f(365,2000)
0.21611945163321847

This works *in Sagemath*. It wouldn’t work in Python : the range of the 
magnitudes of the terms of the *alternating* sum are way too large for the 
precision of Python’s floats, necessary if you want to use math.comb. 
Programming this in Python would need some serious analytical work, or 
using a multiple-precision integer library, which Sage does for you…

[ Re-snip... ]

HTH,


​

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-support+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sage-support/4dfa86e9-d3c8-42cc-8bda-826640da9cf8n%40googlegroups.com.

Reply via email to