Il giorno lunedì 20 marzo 2023 alle 19:10:26 UTC+1 Thomas Passin ha scritto:
> On 3/20/2023 11:21 AM, Edmondo Giovannozzi wrote: 
> > 
> >>> def sum1(): 
> >>> s = 0 
> >>> for i in range(1000000): 
> >>> s += i 
> >>> return s 
> >>> 
> >>> def sum2(): 
> >>> return sum(range(1000000)) 
> >> Here you already have the numbers you want to add. 
> > 
> > Actually using numpy you'll be much faster in this case: 
> > 
> > § import numpy as np 
> > § def sum3(): 
> > § return np.arange(1_000_000, dtype=np.int64).sum() 
> > 
> > On my computer sum1 takes 44 ms, while the numpy version just 2.6 ms 
> > One problem is that sum2 gives the wrong result. This is why I used 
> > np.arange with dtype=np.int64.
> On my computer they all give the same result. 
> 
> Python 3.10.9, PyQt version 6.4.1 
> Windows 10 AMD64 (build 10.0.19044) SP0 
> Processor: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz, 1690 Mhz, 4 
> Core(s), 8 Logical Processor(s)
> > sum2 evidently doesn't uses the python "big integers" e restrict the result 
> > to 32 bits.
> What about your system? Let's see if we can figure the reason for the 
> difference.

I'm using winpython on Windows 11 and the python version is, well, 3.11:

But it is my fault, sorry, I realised now that ipython is importing numpy 
namespace and the numpy sum function is overwriting the intrinsic sum.
The intrinsic sum is behaving correctly and is faster when used in 
sum(range(1_000_000)) then the numpy version.


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to