Home > OS >  Why can I not use linspace on this basic function that contains a for-loop?
Why can I not use linspace on this basic function that contains a for-loop?

Time:03-23

I have a larger, more complex function that essentially boils down to the below function: f(X). Why can't this function take in linspace integers as a parameter? This error is given:

"TypeError: only integer scalar arrays can be converted to a scalar index"

import numpy
from matplotlib import*
from numpy import*
import numpy as np
from math import*
import random
from random import *
import matplotlib.pyplot as plt

def f(x):

    for i in range(x):
        x =1

    return x

xlist = np.linspace(0, 100, 10)

ylist = f(xlist)

plt.figure(num=0)

CodePudding user response:

linspace produces a numpy array, not a list. Don't confuse the two.

In [3]: x = np.linspace(0,100,10)
In [4]: x
Out[4]: 
array([  0.        ,  11.11111111,  22.22222222,  33.33333333,
        44.44444444,  55.55555556,  66.66666667,  77.77777778,
        88.88888889, 100.        ])

The numbers will look nicer if we take into account that linspace includes the end points:

In [5]: x = np.linspace(0,100,11)
In [6]: x
Out[6]: array([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.])

As an array, we can simply add a scalar; no need to write a loop:

In [7]: x   1
Out[7]: array([  1.,  11.,  21.,  31.,  41.,  51.,  61.,  71.,  81.,  91., 101.])

range takes one number (or 3), but never an array (of more than 1 element):

In [8]: for i in range(5): print(i)
0
1
2
3
4

We can't modify i in such a loop, or the "x" used to create the range. But we can write a list comprehension:

In [9]: [i 1 for i in range(5)]
Out[9]: [1, 2, 3, 4, 5]

references:

https://www.w3schools.com/python/ref_func_range.asp

https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

CodePudding user response:

xlist = np.linspace(0, 100, 10)   1

CodePudding user response:

Based on your comment it seems you are just trying to plot a few points. I think your use of range and linspace are redundant and you don't need a loop at all. You do not need a for loop to plot many points, unless you are trying to plot multiple curves or do something fancy with each point. For example, this plots 10 points:

x = np.linspace(0, 100, 10)
y=x*x
plt.plot(x,y,'.')

I think this is a good place to start: https://matplotlib.org/3.5.1/tutorials/introductory/pyplot.html

  • Related