#coding:utf-8
'''多變數非線性方程求解
'''import sympy
import scipy
from scipy import optimize
import numpy as np
from matplotlib import pyplot as plt
from pylab import mpl
mpl.rcparams['font.sans-serif'] = ['fangsong'] # 指定預設字型
mpl.rcparams['axes.unicode_minus'] = false # 解決儲存影象是負號'-'顯示為方塊的問題
'''y - x^3 - 2*x^2 + 1 = 0
y + x^2 - 1 = 0
'''def f(x):
return [x[1] - x[0] ** 3 - 2 * x[0] ** 2 + 1,x[1] + x[0] ** 2 - 1]
result = optimize.fsolve(f,[1,1])
print('result = ',result)
# 使用符號方式求解
x, y = sympy.symbols("x, y")
f_mat = sympy.matrix([y - x**3 -2*x**2 + 1, y + x**2 - 1])
# 求解雅可比矩陣
result = f_mat.jacobian(sympy.matrix([x, y]))
print('result = ',result)
def f_jacobian(x):
return [[-3*x[0]**2-4*x[0], 1], [2*x[0], 1]]
result = optimize.fsolve(f, [1, 1], fprime=f_jacobian)
print('result = ',result)
# 視覺化求解過程
x = np.linspace(-3, 2, 5000)
y1 = x**3 + 2 * x**2 -1
y2 = -x**2 + 1
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y1, 'b', lw=1.5, label=r'$y = x^3 + 2x^2 - 1$')
ax.plot(x, y2, 'g', lw=1.5, label=r'$y = -x^2 + 1$')
x_guesses = [[-2, 2], [1, -1], [-2, -5]]
for x_guess in x_guesses:
sol = optimize.fsolve(f, x_guess)
ax.plot(sol[0], sol[1], 'r*', markersize=15)
ax.plot(x_guess[0], x_guess[1], 'ko')
ax.annotate("", xy=(sol[0], sol[1]), xytext=(x_guess[0], x_guess[1]),
arrowprops=dict(arrowstyle="->", linewidth=2.5))
ax.legend(loc=0)
ax.set_xlabel(r'$x$', fontsize=18)
plt.show()
matlab多變數牛頓方法求解非線性方程組
這本是個作業,但因為各種原因及出錯,這個簡單的 寫了2個多小時,內心不爽。因此寫下部落格記錄。實現如下 clear clc syms u v f1 6 u 3 u v 3 v 3 4 f2 u 2 18 u v 2 16 v 3 1 f f1 f2 df0 diff f,u diff f,v df ...
多變數線性回歸
import numpy as np import pandas as pd import matplotlib.pyplot as plt import cost function import gd function path ex1data2.txt data2 pd.read csv pat...
多變數線性回歸
固定隨機數 x1 numpy.random.random 50 x2 numpy.random.random 50 y 3 0.7 x1 2.3 x2 x numpy.c x1,x2 x numpy.c numpy.ones len x x y numpy.c y m,n x.shape alpha...