[Python-ideas] Add the imath module

Paul Moore p.f.moore at gmail.com
Thu Jul 12 10:30:39 EDT 2018


On 12 July 2018 at 14:30, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 12.07.18 15:15, David Mertz пише:
>>
>> On Thu, Jul 12, 2018, 7:56 AM Serhiy Storchaka <storchaka at gmail.com
>> <mailto:storchaka at gmail.com>> wrote:
>>
>>     * isprime(n)
>>     Tests if n is a prime number.
>>
>>
>> How would you test this? The Miller-Rabin Primality test? For large
>> numbers, iterating through candidate prime divisors is pricey.
>>
>>     * primes()
>>     Returns an iterator of prime numbers: 2, 3, 5, 7, 11, 13,...
>>
>>
>> How would you implements this? Sieve of Eratosthenes is really fun to show
>> students as a Python generator function. But the cached primes DO grow
>> unboundedly as you utilize the generator. Wheel factorization as first pass?
>> Do you cached the first N primes so the each instance of iterator can
>> provide initial elements much faster? What is N?
>
>
> I didn't mean any concrete implementation. Sure there are enough efficient
> and simple. I sometimes need a sequence of prime numbers for solving toy
> problems, and quickly write something like:
>
> def primes(n):
>     return (i for i in range(2, n) if all(i % j for j in primes(int(sqrt(i))
> + 1)))
>
> Having such feature in the stdlib would be very convenient. Any reasonable
> implementation is enough efficient for my purposes.

Agreed, having these functions in the stdlib would be convenient, but
I think it's important that we have at least reasonably performing
implementations (they don't have to be suitable for specialist use,
but they should be performant enough for production, non-specialist
use). IMO, the statistics module got this balance right - good enough
for general use, but specialists will want something better.

I'm -1 on having inefficient versions like your primes(n)
implementation above in the stdlib. People will use them not realising
they may not be suitable for anything other than toy problems.

I'd be interested in the following (which is mostly a duplicate of your list)

* factorial
* gcd
* binom
* isprime (it's important to be clear if this is a guaranteed check,
or a probabilistic one like Miller Rabin)
* primes (an infinite generator of primes)
* factors (generates the prime factors of a number, in increasing
order, so list(factors(12)) = [2, 2, 3])

Your divide_and_round might be nice, but there are multiple common
ways of rounding 0.5 (up, down, towards 0, away from 0, to even, to
odd, ...) Your implementation does round to even, but that's not
necessarily the obvious one (schools often teach round up or down, so
use of your implementation in education could be confusing).

> Because cmath. But if most core developers prefer intmath, I have no objections.

I prefer imath as a parallel with cmath, as you say. But it's not a
big deal to me.

Paul


More information about the Python-ideas mailing list