I'm trying to solve this system of non linear equations using scipy.optimize.fsolve , I took this from an example in one other post here
my system of equation is the follow :
for i in range(len(self.time)-1):
def equations(variable):
k1,k2 = variable
f1 = -k1 + self.f(self.time[i]+ (0.5+np.sqrt(3)/6)* self.dt , self.u[i]+0.25*self.dt* k1+ (0.25+ np.sqrt(3)/6)*self.dt*k2)
f2 = -k2 + self.f(self.time[i]+ (0.5-np.sqrt(3)/6)* self.dt , self.u[i]+(0.25-np.sqrt(3)/6)*self.dt *k1 + 0.25*self.dt* k2)
return (f1,f2)
k1,k2 = fsolve(equations,(5,5))
when I run the code I got :
TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (2,) but it is (2, 1).
EDIT I don't know why this mismatch and how to fix it .. I tried :
for i in range(len(self.time)-1):
ui = self.u[i]
ti = self.time[i]
def equations(variable):
k1,k2 = variable
f1 = -k1 + self.f(ti+ (0.5+np.sqrt(3)/6)* self.dt , ui+0.25*self.dt* k1+ (0.25+ np.sqrt(3)/6)*self.dt*k2)
f2 = -k2 + self.f(ti+ (0.5-np.sqrt(3)/6)* self.dt , ui+(0.25-np.sqrt(3)/6)*self.dt *k1 + 0.25*self.dt* k2)
return (f1,f2)
k1,k2 = fsolve(equations,(1,1))
EDIT I've tried : return np.array([f1,f2])
and I got the same mismatch error!
Apparently the problem is here:
Shape should be (2,) but it is (2, 1).
Even if you have just two values, in numpy it is different to have an "unidimensional vector" with two values, and a "bidimensional matrix" with two values.
I suggest that you call ravel()
or flatten()
to convert your (2,1)
shape to a (2,)
shape:
import numpy as np
a = np.array([[1,2]])
print("before:")
print("array: ", a)
print("shape: ", a.shape)
print()
b = a.ravel()
print("after:")
print("array: ", b)
print("shape: ", b.shape)
> before:
> array: [[1 2]]
> shape: (1, 2)
> after:
> array: [1 2]
> shape: (2,)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.