linregress and polyfit

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Sep 19 10:37:09 EDT 2013


On 18 September 2013 20:57, Dave Angel <davea at davea.name> wrote:
> On 18/9/2013 09:38, chitturk at uah.edu wrote:
>
>> Thanks - that helps ... but it is puzzling because
>>
>> np.random.normal(0.0,1.0,1) returns exactly one
>> and when I checked the length of "z", I get 21 (as before) ...
>>
>>
>
> I don't use Numpy, so this is just a guess, plus reading one web page.
>
> According to:
> http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html
>
> the 3rd argument to normal should be a tuple.  So if you want a single
> element, you should have made it (1,)

Numpy accepts ints in place of shape tuples so this makes no difference.

> As for checking the 'length of "z"' did you just use the len() function?
> That just tells you the first dimension.  Have you tried simply printing
> out "z" ?

Exactly. What you need to check is the shape attribute (converting to
numpy array first if necessary):

>>> import numpy as np
>>> a = np.random.normal(0, 1, 1)
>>> a
array([-0.90292348])
>>> a.shape
(1,)
>>> a[0]
-0.90292348393433797
>>> np.array(a[0])
array(-0.902923483934338)
>>> np.array(a[0]).shape
()
>>> [a, a]
[array([-0.90292348]), array([-0.90292348])]
>>> np.array([a, a])
array([[-0.90292348],
       [-0.90292348]])
>>> np.array([a, a]).shape
(2, 1)
>>> np.random.normal(0, 1, 2).shape
(2,)

The square brackets in 'array([-0.90292348])' indicate that numpy
considers this to be a 1-dimensional array of length 1 rather than a
scalar value (which would have an empty shape tuple).


Oscar



More information about the Python-list mailing list