import numpy as np
a = 3.9 #m
L = 7.8 #m
x = np.arange(0,L+0.1,0.1)
def fun_v():
for value in x:
if 0 < x < a :
V= P*(1-(a/L))
if a < x < L :
V= -P*(a/L)
return (V)
V = fun_v()
print('V =',V)
#ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Advertisement
Answer
The issues are the following:
You are comparing an array instead of a value in a condition, which is ambiguous.
Try0 < value < ainstead0 < x < aTo give an example of what you are doing:
- You are first assigning the
xlike[0, 0.1, 0.2, 0.3 ... ] - Then you are comparing
0 < [0, 0.1, 0.2, 0.3 ... ] < 3.9at line0 < x < a
- You are first assigning the
Also, the variable
Pis not defined. You will need to provide a value ofPlike the ones you provide foraandL.To get an array of
Vvalues, you will need to push the calculatedVvalues in an empty array or you can use themapfunction.
A working example:
import numpy as np
a = 3.9
L = 7.8
P = 10 # P is defined
x = np.arange(0,L+0.1,0.1)
def fun_v():
arr = [] # empty array is initialized
for value in x:
if 0 < value < a : # value is compared instead of x
V = P*(1-(a/L))
arr.append(V) # V is pushed after calculation
if a < value < L :
V = -P*(a/L)
arr.append(V)
return arr # return the array of v values
V = fun_v()
print(V)