What is the simplest method to get a vector result?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 24 10:06:25 EDT 2014


On Thu, 24 Jul 2014 05:53:12 -0700, fl wrote:

> Hi,
> I have read a lot about Python, but it still has a problem now on a
> simple exercise. For example, I want to generate a sine curve. First, I
> get a time sequence:
> 
> index=range(100)
> 
> I import math module, try to calculate sine with
> 
> math.sin(index*math.pi/2)
> 
> but it fails.
> 
> It is possible to use a for loop, but I don't know how to save each
> result to an array.

That is a fundamental, basic part of programming in Python. If you don't 
learn the basics, you will never be a good programmer. Have you done any 
Python tutorials? It's not enough to read them, you must actually do the 
work.

This might get you started:


results = []  # Start with an empty list.
for value in range(100):
    results.append(math.sin(value))


but that probably will not give you the results you are hoping for, as 
sin expects the angles to be given in radians.

Perhaps you mean to scale the angles over a full circle?


tau = 2*math.pi  # number of radians in a full circle
angles = []
values = []
for i in range(100):
    angle = i*tau/100.0
    angles.append(angle)
    values.append(math.sin(angle))


Alternatively, here's a slightly shorter way:

angles = [i*tau/100.0 for i in range(100)]
values = [math.sin(angle) for angle in angles]



-- 
Steven



More information about the Python-list mailing list