ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 12 Jun 2017 11:51:13 -0500How to create a nonzero vector?http://ask.sagemath.org/question/37918/how-to-create-a-nonzero-vector/Hi. I would like to create a nonzero vector, for example, a vector of 100 elements of 1. I can do this with a for loop, but I'm not sure if there's a faster way to do it, similar to zero_vector(). Thanks.Mon, 12 Jun 2017 10:07:02 -0500http://ask.sagemath.org/question/37918/how-to-create-a-nonzero-vector/Answer by mforets for <p>Hi. I would like to create a nonzero vector, for example, a vector of 100 elements of 1. I can do this with a for loop, but I'm not sure if there's a faster way to do it, similar to zero_vector(). Thanks.</p>
http://ask.sagemath.org/question/37918/how-to-create-a-nonzero-vector/?answer=37919#post-id-37919here are some alternatives:
sage: %timeit vector([1. for i in range(1000)])
100 loops, best of 3: 3.14 ms per loop
sage: %timeit ones_matrix(RDF, 1000, 1)
125 loops, best of 3: 4.36 ms per loop
sage: %%time
....: v = zero_vector(RDF, 1000)
....: for i in range(1000):
....: v[i] = 1
....:
CPU times: user 2.39 ms, sys: 759 us, total: 3.15 ms
Wall time: 4.5 ms
just a list:
sage: %timeit [1. for i in range(1000)]
100 loops, best of 3: 2 ms per loop
with NumPy:
sage: import numpy as np
sage: %timeit np.ones(1000)
The slowest run took 9.23 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.9 us per loop
Mon, 12 Jun 2017 11:51:13 -0500http://ask.sagemath.org/question/37918/how-to-create-a-nonzero-vector/?answer=37919#post-id-37919