Cord Kaldemeyer - 1 year ago 246

Python Question

I am trying to solve the following simple system of non-linear equations (Source(second example)):

`(I) y - x^2 = 7 - 5x`

(II) 4y - 8x = -21

which should have only one solution (x=3.5, y=1.75).

My current approach using the scipy stack is the following:

`from scipy.optimize import fsolve`

def equations(p):

x, y = p

return (y - x**2 -7 + 5*x, 4*y - 8*x + 21)

x, y = fsolve(equations, (5, 5))

print(equations((x, y)))

and yields the following (which is not the result):

`(0.0, 0.0)`

I have already tried different starting estimates but it doesn't deliver the right solution.

What's wrong with my approach? Am I missing something?

Thanks in advance!

Answer Source

This works perfectly fine:

```
In [1]: %paste
from scipy.optimize import fsolve
def equations(p):
x, y = p
return (y - x**2 -7 + 5*x, 4*y - 8*x + 21)
x, y = fsolve(equations, (5, 5))
print(equations((x, y)))
## -- End pasted text --
(0.0, 0.0)
In [2]: x
Out[2]: 3.5000000414181831
In [3]: y
Out[3]: 1.7500000828363667
```

`equations(x, y)`

being `(0, 0)`

means that both `y - x**2 -7 + 5*x`

and `4*y - 8*x + 21`

are 0.

Maybe you got confused and meant to `print(x, y)`

instead of `print(equations(x, y))`

?