[Numpy-discussion] Can numpy catch this error for me?

Partridge, Matthew BGI SYD Matthew.Partridge at barclaysglobal.com
Tue Apr 7 17:49:50 EDT 2009


 
> On Tue, Apr 7, 2009 at 14:19, Nathaniel Peterson 
> <nathanielpeterson08 at gmail.com> wrote:
> >
> > import numpy as np
> > import operator
> > np.seterr(all='raise')
> > a=np.arange(1)+1
> > print(a.dtype)
> > # int32
> > for num in range(1,17):
> >     a=np.arange(num)+1
> >     b=np.multiply.reduce(a)
> >     print('%s! = %s'%(num,b))
> > #     c=reduce(operator.mul,range(1,num+1))
> > #     assert(b==c)
> >
> > The code above outputs
> >
> > int32
> > 1! = 1
> > 2! = 2
> > 3! = 6
> > 4! = 24
> > 5! = 120
> > 6! = 720
> > 7! = 5040
> > 8! = 40320
> > 9! = 362880
> > 10! = 3628800
> > 11! = 39916800
> > 12! = 479001600
> > 13! = 1932053504
> > 14! = 1278945280
> > 15! = 2004310016
> > 16! = 2004189184
> >
> > The results for 14! and above are wrong due to overflow of 
> the int32 
> > data type.
> > Is there a way to setup numpy so it will raise an error 
> when this occurs?
> 
> No, sorry.

Of course one can get the int behaviour by specifying dtype=object.
(This way you get the longer int behaviour and the *lack of speed* to go with it.)

for num in range(1,17):
    a=np.arange(num, dtype=object)+1
    b=np.multiply.reduce(a)
    print('%s! = %s'%(num,b))

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000

matt

 
--
 
This message and any attachments are confidential, proprietary, and may be privileged. If this message was misdirected, Barclays Global Investors (BGI) does not waive any confidentiality or privilege. If you are not the intended recipient, please notify us immediately and destroy the message without disclosing its contents to anyone. Any distribution, use or copying of this e-mail or the information it contains by other than an intended recipient is unauthorized. The views and opinions expressed in this e-mail message are the author's own and may not reflect the views and opinions of BGI, unless the author is authorized by BGI to express such views or opinions on its behalf. All email sent to or from this address is subject to electronic storage and review by BGI. Although BGI operates anti-virus programs, it does not accept responsibility for any damage whatsoever caused by viruses being passed.



More information about the NumPy-Discussion mailing list