Home > Net >  how do I make a for loop understand that I want it to run i for all values inside x. x being a defin
how do I make a for loop understand that I want it to run i for all values inside x. x being a defin

Time:10-24

My code right now is as it follows:

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

"""
TITLE
"""

def f(x,y):
  for i in range(len(x)):
    y.append(exp(-x[i]) - sin (pi*x[i]/2))

def ddxf(x,y2):
  for i in range(len(x)):
    y2.append(-exp(-x[i]) - (pi/2)*cos(pi*x[i]/2))
  
y = []
y2 = []
f(x, y)  
x = np.linspace(0, 4, 100)

plt.title('Graph of function x')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.plot(x, y, 'g')
plt.grid(True)
plt.show()

x0 = float(input("Insert the approximate value of the first positive root: "))

intMax = 100
i = 0
epsilon = 1.e-7

while abs(f(x0,y)) > epsilon and i < intMax:
  x1 = x0 - (f(x0))/(ddxf(x0))
  x0 = x1
  i  = 1

print (i)
print (x1)

I get this error when running the program. it seems that (len(x)) cannot be used if x isnt a string. which doesn't make sense to me. if the array has a len and isn't infinite, why (len(x)) cant read his length? anyway, please help me. hope I made myself clear

Error

CodePudding user response:

Regarding the error: You are using x before defining it. In your code, you first use f(x, y) and only after that you actually define what x is (namely x = np.linspace(0, 4, 100)). You probably want to swap these two lines to fix the issue.

Regarding the question in the title: len(x) should be fine to get the length of a list. However, in Python you don't need to go through a list like that. You can instead use for element_name in list_name: This will essentially go through list_name element by element and make it available to you with the name element_name. There is also something called list comprehensions in Python - you might want to take a look at those and see whether you can apply it to your code.

  • Related