设计一个窗口程序: 想要实现四种功能:
1.设置按钮🔘1 : 点击 ------ 弹出三行输入框 -----输入函数表达式-----显示其Latex数学表达式----输入三个函数 分别为 f_1(x) 、 f_2(x) 、f_3(x)-------点击 ‘run’ 按钮🔘 ------ 传入三个函数进行 计算围成的封闭的区域的面积,并画图。
2.设置按钮🔘2 : 点击-------弹出一行输入框------ 输入函数表达式-----显示其Latex数学表达式------点击‘Run’按钮------计算该函数的极值。
3.设置按钮🔘3 : 点击 ------ 程序从准备好的Excel文件中提取数据------输出一个样条近似函数 并绘制图像。
4.设置按钮🔘4: 点击 ------- 输入第二类Fredholm方程的右边f(x)------解方程SolveFredholm ----输出结果。
代码测试结果:
run.....
首先弹出“my homework”窗口界面 (窗口显示的图像可自行更换)
屏幕左上角:有functionality菜单栏
可以点击:
分别对应不同的功能:例如功能 1:
输入线性数学表达式,点击按钮“show”画布中可以显示其对应的latex表达式:如下
功能2~4同理可测试。
以下是完整代码
import tkinter as tk # 使用Tkinter前需要先导入
from cmath import e
from tkinter import *
from tkinter.simpledialog import askinteger, askfloat, askstring
from tkinter.filedialog import askopenfilename, askopenfilenames, asksaveasfilename, askdirectory
from tkinter.messagebox import showinfo, showwarning, showerror
import os
import scipy as scp
from tkinter import *
from tkinter import ttk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pylab
import numpy as np
import openpyxl
from numpy import exp
from openpyxl.utils import get_column_letter, column_index_from_string
import pylab
import numpy as np
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
import xlsxwriter
import xlwt
import numpy as np
from scipy.optimize import minimize_scalar
import latexify
import sympy as sy
from sympy import lambdify
import numpy.linalg as LA
import matplotlib.pyplot as plt
from scipy.special.orthogonal import p_roots
import time
import scipy
from scipy import integrate
global F1,F2,F3
def functionformate(f):
if f.find('e^') != -1:
f = f.replace('e^', 'sy.exp')
if f.find('^') != -1:
f = f.replace('^', '**')
if f.find('cos') != -1:
f = f.replace('cos', 'sy.cos')
if f.find('sin') != -1:
f = f.replace('sin', 'sy.sin')
if f.find('pi') != -1:
f = f.replace('pi', 'sy.pi')
return f
#os.system("python filename.py")
# 第1步,实例化object,建立窗口window
from spyder_kernels.utils.lazymodules import numpy
window = tk.Tk()
# 第2步,给窗口的可视化起名字
window.title('My HomeWork')
# 第3步,设定窗口的大小(长 * 宽)
window.geometry('640x241') # 这里的乘是小x
# 第4步,加载 wellcome image
# 第4步,在图形界面上创建 500 * 200 大小的画布并放置各种元素
canvas = tk.Canvas(window, width=640, height=241, bg='green')
image_file = tk.PhotoImage(file='pic4.png')
image = canvas.create_image(320, 0, anchor='n', image=image_file)
canvas.pack(side='top')
tk.Label(window, text='Wellcome', font=('Arial', 16)).pack()
# 第10步,定义一个函数功能,用来代表菜单选项的功能,这里为了操作简单,定义的功能比较简单
#Определение функции, используемой для представления параметров меню.
#task--1 弹出一个窗口 -- 显示三个输入框 ,传入三个函数
def no1():
win = tk.Tk()
win.title('TASK-1')
win.geometry('700x450')
# Create a Frame object 创建框架对象
frame = Frame(win)
frame.pack()
var1 = StringVar()
entry1 = Entry(frame, width=70, textvariable=var1)
entry1.pack()
var2 = StringVar()
entry2 = Entry(frame, width=70, textvariable=var2)
entry2.pack()
var3 = StringVar()
entry3 = Entry(frame, width=70, textvariable=var3)
entry3.pack()
# Add a label widget in the frame 在框架中添加标签小部件
label = Label(frame)
label.pack()
fig = matplotlib.figure.Figure(figsize=(7, 4), dpi=100)
wx = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
# Set the visibility of the Canvas figure 设置画布图形的可见性
wx.get_xaxis().set_visible(False)
wx.get_yaxis().set_visible(False)
# print(f1)
# Get the Entry Input
def showformula():
x1 = sy.symbols('x1')
x2 = sy.symbols('x2')
F1 = entry1.get()
F2 = entry2.get()
F3 = entry3.get()
#F1 = 'e^(-x1)+3'
#F2 = '2*x1-2'
#F3 = '1/x2'
tmptext1 = "$f_{2}(x1)=" + str(sy.latex(eval(functionformate(F1)))) + "$"
tmptext2 = "$f_{2}(x1)=" + str(sy.latex(eval(functionformate(F2)))) + "$"
tmptext3 = "$f_{3}(x2)=" + str(sy.latex(eval(functionformate(F3)))) + "$"
wx.clear()
wx.text(0.2, 0.8, tmptext1, fontsize=20)
wx.text(0.2, 0.6, tmptext2, fontsize=20)
wx.text(0.2, 0.4, tmptext3, fontsize=20)
canvas.draw()
def calculate():
x1 = sy.symbols('x1')
x2 = sy.symbols('x2')
F1 = entry1.get()
F2 = entry2.get()
F3 = entry3.get()
def f1(x1):
return eval(functionformate(F1))
def f2(x1):
return eval(functionformate(F2))
def f3(x2):
return eval(functionformate(F3))
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# plt.legend(loc= 'lower left') # 设置图例位置location
plt.ylim(-10, 10) # y轴显示区间
plt.xlim(-1, 3) # x轴显示区间
ax = plt.gca() # 可以使用 plt.gcf()和 plt.gca()获得当前的图表和坐标轴(分别表示 Get Current Figure 和 Get Current Axes)
ax.xaxis.set_ticks_position('bottom') # 设置x轴为下边框
ax.spines['bottom'].set_position(('data', 0)) # spines是脊柱的意思,移动x轴
ax.spines['top'].set_color('none') # 设置顶部支柱的颜色为空
ax.spines['right'].set_color('none') # 设置右边支柱的颜色为空
plt.grid(True, linestyle='--', alpha=0.5) # 网格
X1 = np.arange(-1, 3, 0.1) # x范围
X2 = np.ma.masked_array(X1, mask=((X1 < 0.000001) & (X1 > -0.000001))) # 反比例函数去掉X为零的情况
FF1 = np.exp(-X1) + 3 # 指数函数
FF2 = 2 * X1 - 2 # 一次函数
FF3 = 1 / X2 # 反比例函数
# Find the roots of the equation f = g by the dichotomy method
def root(f, g, a, b, eps1):
while b - a > eps1:
# 用二分法 求f = g 方程的根
x = (a + b) / 2
y = f(x) - g(x)
ya = f(a) - g(a)
yb = f(b) - g(b)
if y * ya < 0:
b = x
elif y * yb < 0:
a = x
r = "%.4f" % ((a + b) / 2)
return r
# Calculate the function of the integral
def integral(f, a, b, eps2):
# 设置初始积分
n = 20
# n对应的积分值
R = [] # 一个空的list
I = 0
h = (b - a) / n
# 计算积分
for i in range(0, n - 1):
I += (f(a + (i + 0.5) * h))
R.append(h * I) # 记录h*I 的值
while (1):
# 更新
n *= 2
I = 0
h = (b - a) / n
# 计算
for i in range(0, n - 1): # 从0 ~n-1的循环
I += (f(a + (i + 0.5) * h)) # 矩形公式 'Прямоугольная формула'
R.append(h * I)
# 判断
if (abs(R[-1] - R[-2]) / 3 < eps2):
break
c = [] # 存下每个积分点的横坐标
for i in range(0, n - 1):
c.append(a + h * i)
# print("R:", R[-1])
return c, R[-1]
# Нарисуйте область, заключенную в функции
def drawRomberg(f1, f2, a, b, eps2, n): # 画出求积部分
x1, y1 = integral(f1, a, b, eps2)
x1_ = []
for i in range(len(x1)):
if i % n == 0:
x1_.append(x1[i])
if i == len(x1) - 1:
x1_.append(x1[i])
for i in x1_:
line = [i, f1(i), i, f2(i)]
plt.plot(line[::2], line[1::2], color='red',
linewidth=1, linestyle="--")
if __name__ == '__main__': # “if __name__==’__main__:”也像是一个标志,象征着Java等语言中的程序主入口,告诉其他程序员,代码入口在此——这是“if __name__==’__main__:”这条代码的意义之一。
# 计算四个交点的坐标 ; Вычислите координаты четырех точек пересечения
x4 = float("%.4f" % float(root(f1, f2, 2, 3, 0.001)))
y4 = "%.4f" % float(f2(x4))
x2 = float("%.4f" % float(root(f1, f3, 0.1, 1, 0.001)))
y2 = "%.4f" % float(f3(x2))
x3 = float("%.4f" % float(root(f2, f3, 1, 2, 0.001)))
y3 = "%.4f" % float(f2(x3))
x1 = float("%.4f" % float(root(f2, f3, -1, -0.1, 0.001)))
y1 = "%.4f" % float(f2(x1))
print("x1:%.4f" % float(x1), "y1:%.4f" % float(y1))
print("x2:%.4f" % float(x2), "y2:%.4f" % float(y2))
print("x3:%.4f" % float(x3), "y3:%.4f" % float(y3))
print("x4:%.4f" % float(x4), "y4:%.4f" % float(y4))
# 画出初始的三条函数;Нарисуйте три исходные функции
plt.plot(X1, FF1, linewidth=1.5, linestyle="-", label="f1")
plt.plot(X1, FF2, linewidth=1.5, linestyle="-", label="f2")
plt.plot(X2, FF3, linewidth=1.5, linestyle="-", label="f3")
# 画出四个交点围成的三角形
polygon = [[float(x2), float(y2)], [float(x3), float(y3)], [
float(x4), float(y4)]]
# line_area = polygon+[polygon[0]]
# plt.plot([i[0] for i in line_area], [i[1] for i in line_area])
# 画出三个焦点
plt.scatter(polygon[0][0], polygon[0][1], s=50, c='r')
plt.scatter(polygon[1][0], polygon[1][1], s=50, c='r')
plt.scatter(polygon[2][0], polygon[2][1], s=50, c='r')
# 计算面积; Результаты расчетов
I = integral(f1, float(x2), float(x4), 0.001)[1] - integral(f2, float(x3),
float(x4), 0.001)[1] - \
integral(f3, float(x2), float(x3), 0.001)[1]
# 画出求积部分
drawRomberg(f1, f3, float(x2), float(x3), 0.001, 80)
drawRomberg(f1, f2, float(x3), float(x4), 0.001, 80)
# 显示计算结果
plt.text(1.5, 6, "I = {}".format("%.4f" % float(I)))
# r" "中间为LaTex语法表示的公式
# plt.text(0, 0, r"$\mathrm{f1}(x) = \exp{\left({-x}\right)} + {3}$",horizontalalignment='center', fontsize=20)
# 显示
plt.legend(loc='upper left')
plt.show()
b1 = tk.Button(win, text='Show_Formula', width=10,height=2, command=showformula)
b1.pack()
b2 = tk.Button(win, text='Run', width=10, height=2, command=calculate)
b2.pack()
def no2():
win2 = tk.Tk()
win2.title('TASK-2')
win2.geometry('700x450')
# Create a Frame object 创建框架对象
frame = Frame(win2)
frame.pack()
# Create an Entry widget
var = StringVar()
entry = Entry(frame, width=70, textvariable=var)
entry.pack()
# Add a label widget in the frame 在框架中添加标签小部件
label = Label(frame)
label.pack()
# Define the figure size and plot the figure 定义尺寸 并 绘制
fig = matplotlib.figure.Figure(figsize=(7, 4), dpi=100)
wx = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
# Set the visibility of the Canvas figure 设置画布图形的可见性
wx.get_xaxis().set_visible(False)
wx.get_yaxis().set_visible(False)
def showformula():
# Get the Entry Input
x = sy.symbols('x')
f = entry.get()
tmptext = "$f(x)=" + str(sy.latex(eval(functionformate(f)))) + "$"
wx.clear()
wx.text(0.2, 0.8, tmptext, fontsize=20)
canvas.draw()
def calculate():
#x = sy.symbols('x')
from sympy.abc import x
F = entry.get()
def f(x):
return eval(functionformate(F))
ff = lambdify((x), f(x), modules=['numpy'])
tmptext = "$f(x)=" + str(sy.latex(eval(functionformate(F)))) + "$"
res = minimize_scalar(ff, method='brent')
print(res.x)
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
x = np.linspace(-4, 4, 100)
y = ff(x)
t = np.linspace(ff(res.x), ff(4), 100)
plt.plot([res.x] * len(x), t, color="red", label="$x = res.x$", linewidth=2)
plt.plot(x, y, color="orange", label=tmptext, linewidth=2)
plt.legend()
plt.show()
b1 = tk.Button(win2, text='Show_Formula', width=10, height=2, command=showformula)
b1.pack()
b2 = tk.Button(win2, text='Run', width=10, height=2, command=calculate)
b2.pack()
def no3():
win3 = tk.Tk()
win3.title('TASK-3')
win3.geometry('400x200')
# 接收一个字符串
# 第4步,在图形界面上创建一个标签label用以显示并放置
l = tk.Label(win3, bg='green', fg='white', width=200, text='please input excelfile_name .xlsx: ')
l.pack()
# Create an Entry widget
var = StringVar()
entry = Entry(win3, width=10, textvariable=var)
entry.pack()
def getData(name_excel):
# 打开excel文件
wb = openpyxl.load_workbook(name_excel)
# 获取表
sheet = wb.active
# 1.获取整个一行的单元格
max_column = sheet.max_column # 获取最大列数 -- 2列
column = get_column_letter(max_column) # 获取最大列数对应的字母列号
# 获取整个列的单元格
max_row = sheet.max_row # 最大的行数 === 31
columnX = sheet['A1':'A%d' % max_row]
columnY = sheet['B1':'B%d' % max_row]
x = []
y = []
# 获取B列对应的所有单元格对象
for column_cells in columnX:
for cell in column_cells:
x.append(cell.value)
print(x)
for column_cells in columnY:
for cell in column_cells:
y.append(cell.value)
print(y)
return x, y
def Analyze():
# Get the Entry Input
name_excel = entry.get()
x, y = getData(name_excel)
z1 = np.polyfit(x, y, 3) # 曲线拟合,返回值为多项式的各项系数(Приведение кривых в соответствие с коэффициентами многочлена)
p1 = np.poly1d(z1) # 返回值为多项式的表达式,也就是函数式子(Вернуться к выражению многочлена, которое является функциональным форматом)
print(p1)
y_pred = p1(x) # 根据函数的多项式表达式,求解 y (В зависимости от многочленного выражения функции, решение y)
plot1 = pylab.plot(x, y, '*', label='original values')
plot2 = pylab.plot(x, y_pred, 'r', label='fit values')
pylab.title('')
pylab.xlabel('')
pylab.ylabel('')
pylab.legend(loc=3, borderaxespad=0., bbox_to_anchor=(0, 0))
pylab.show()
pylab.savefig('p1.png', dpi=200, bbox_inches='tight')
wb = xlwt.Workbook()
# 添加一个表
ws = wb.add_sheet('test')
# 3个参数分别为行号,列号,和内容
# 需要注意的是行号和列号都是从0开始的
ws.write(0, 0, z1[0])
ws.write(0, 1, float(z1[1]))
ws.write(0, 2, float(z1[2]))
ws.write(0, 3, float(z1[3]))
# 保存excel文件
wb.save('./test.xls')
tk.Button(win3, text='Start', command=Analyze).pack()
def no4():
win4 = tk.Tk()
win4.title('TASK-4')
win4.geometry('800x600')
# 第4步,在图形界面上创建一个标签label用以显示并放置
l3 = tk.Label(win4, bg='green', fg='white', width=200, text='please input K(s,t) : ')
l3.pack()
# Create an Entry widget
var3 = StringVar()
entry3 = Entry(win4, width=10, textvariable=var3)
entry3.pack()
l4 = tk.Label(win4, bg='green', fg='white', width=200, text='please input f(s) : ')
l4.pack()
var4 = StringVar()
entry4 = Entry(win4, width=10, textvariable=var4)
entry4.pack()
l = tk.Label(win4, bg='green', fg='white', width=200, text='please input K(s,t) : ')
l.pack()
# Create an Entry widget
var = StringVar()
entry = Entry(win4, width=10, textvariable=var)
entry.pack()
l2 = tk.Label(win4, bg='green', fg='white', width=200, text='please input x(t) : ')
l2.pack()
var2 = StringVar()
entry2 = Entry(win4, width=10, textvariable=var2)
entry2.pack()
# Create a Frame object 创建框架对象
frame = Frame(win4)
frame.pack()
# Add a label widget in the frame 在框架中添加标签小部件
label = Label(frame)
label.pack()
# Define the figure size and plot the figure 定义尺寸 并 绘制
fig = matplotlib.figure.Figure(figsize=(7, 4), dpi=100)
wx = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
# Set the visibility of the Canvas figure 设置画布图形的可见性
wx.get_xaxis().set_visible(False)
wx.get_yaxis().set_visible(False)
def start1():
from sympy.abc import s,t
K2 = entry3.get()
f2 = entry4.get()
def k1(s,t):
return eval(functionformate(K2))
def fs(s):
return eval(functionformate(f2))
k = lambdify((s,t), k1(s,t), modules=['numpy'])
f = lambdify((s), fs(s), modules=['numpy'])
def SolveFredholm(k, f, a, b, num, **kwargs): # 声明函数后那个箭头:"->" 是返回值的注释
gamma: float = 1e-3
# need num to be odd to apply Simpson's rule num需要奇数才能应用Simpson规则
if (num % 2) == 0:
num += 1
# set defaults for s params
if "smin" in kwargs.keys():
smin = kwargs["smin"]
else:
smin = a
if "smax" in kwargs.keys():
smax = kwargs["smax"]
else:
smax = b
if "snum" in kwargs.keys():
snum = kwargs["snum"]
else:
snum = 2 * num
# get grid for s
sgrid = numpy.linspace(smin, smax, snum) # 在指定的间隔内返回均匀间隔的数字
# get grid for y
ygrid = numpy.linspace(a, b, num)
# get quadrature weights 获取正交权重
weights = simpson(num)
# create the quadrature matrix 创建正交矩阵
ksqur = weights * k(sgrid[:, numpy.newaxis], ygrid)
# Make H matrix 制作H矩阵
if gamma != 0:
Hmat = makeH(num)
AAgH = (ksqur.T @ ksqur) + (gamma * Hmat)
else:
AAgH = ksqur.T @ ksqur
# find the gvalues (/num) by solving the system of equations 通过求解方程组求gvalue(/num)
ggrid = numpy.linalg.solve(AAgH, ksqur.T @ f(sgrid))
# combine the s grid and the g grid 组合s网格和g网格
print(gamma)
return numpy.array([ygrid, (ggrid * num / (b - a))])
def makeH(dim: int):
# create (symmetric) diagonal vectors 创建(对称)对角向量
d2 = numpy.ones(dim - 2)
d1 = numpy.concatenate(([-2], numpy.repeat(-4, dim - 3), [-2]))
d0 = numpy.concatenate(([1, 5], numpy.repeat(6, dim - 4), [5, 1]))
# make matrix with diagonals
Hmat = numpy.diag(d1, 1) + numpy.diag(d2, 2)
Hmat = Hmat + Hmat.T
numpy.fill_diagonal(Hmat, d0)
return Hmat
def simpson(dim: int): # 辛普森法则: 是一种数值积分方法 , 求得定积分的数值近似解
if dim > 2 and (dim % 2) == 1: # dim是奇数
tiles = numpy.tile([4, 2], dim // 2) # 创建一个矩阵
return numpy.concatenate(([1], tiles[0: dim - 2], [1])) / 3 # list之间的拼接
else:
raise ValueError("Simpson's rule requires an odd number of endpoints")
# %%
def smooth(v: numpy.ndarray):
dim = len(v)
smat = numpy.diag(
numpy.concatenate(([1], numpy.repeat(0.5, dim - 1)))
) + numpy.diag(numpy.repeat(0.5, dim - 1), -1)
return smat @ v
miu = 0.2
# define kernel
# def k(s, t):
# return miu / (miu ** 2 + (t - s) ** 2)
#
# # define free function
# def f(s):
# return np.cos(np.pi * s)
# define true solution
def trueg(s):
return k(0, s)
# apply the solver
s, g = SolveFredholm(k, f, a=-1, b=1, num=1000, smin=-1, smax=1)
# plot functions
figure = plt.figure()
plt.plot(s, g)
plt.plot(s, trueg(s))
plt.legend(["Estimate", "True Value"])
plt.xlabel("s")
plt.ylabel("g(s)")
figure.set_dpi(100) # 以每英寸点数为单位设置图形的分辨率。
figure.set_size_inches(8, 5)
plt.show()
print('success')
def start2():
plt.ylim(-1, 10) # y轴显示区间
plt.xlim(0, 1) # x轴显示区间
from sympy.abc import s, t
K1 = entry.get()
x1 = entry2.get()
def k2(s, t):
return eval(functionformate(K1))
def xt(t):
return eval(functionformate(x1))
function_k = lambdify((s, t), k2(s, t), modules=['numpy'])
function_x = lambdify((t), xt(t), modules=['numpy'])
t = np.linspace(0, 1, 100)
y = function_x(t)
plt.grid()
plt.plot(t, y)
def gauss_xw(
m=100): # By default, 100 points are used to calculate Gauss -- Legendre node xi and weight, and x and w arrays are returned
x, w = p_roots(m + 1)
return x, w
def gauss_solve_f(x, w, lamda, a, b, n): # 参数n>=1
c = (b - a) / 2
s = (b - a) / 2 * x + (a + b) / 2 # Изменить интервал [a, b] на [- 1,1]
h = (b - a) / (n)
t = [a + i * h for i in range(0, n + 1)] # Изометрическое деление a=t0<t1<... <tn=b
return [sum([c * w[k] * lamda * function_x(s[k]) * hat_f(i, s[k], a, b) -
c * w[k] * sum([c * w[j] * function_k(s[j], s[k]) * function_x(s[j]) * hat_f(i, s[k], a, b) \
for j in range(len(s))]) for k in range(len(s))]) \
for i in range(len(t))]
def hat_f(j, x, a, b):
h = (b - a) / (n)
t = [a + i * h for i in range(0, n + 1)]
if j == 0:
if x >= t[0] and x <= t[1]:
return 1 - abs(x - t[0]) / h
else:
return 0
if j == n:
if t[n - 1] <= x and x <= t[n]:
return 1 - abs(x - t[n]) / h
else:
return 0
if j > 0 and j < n:
if t[j - 1] <= x and x <= t[j + 1]:
return 1 - abs(x - t[j]) / h
else:
return 0
def elements_of_matrix(x, w, a, b, lamda, n):
c = (b - a) / 2
s = (b - a) / 2 * x + (a + b) / 2 # 把区间[a,b]变化到[-1,1]
h = (b - a) / (n)
t = [a + i * h for i in range(0, n + 1)] # 等距划分a=t0<t1<...<tn=b
A = []
for i in range(len(t)):
A.append([scp.integrate.quad(lambda x: lamda * hat_f(i, x, a, b) * hat_f(j, x, a, b), a, b)[0] - \
sum([c * w[k] * sum(
[c * w[e] * function_k(s[e], s[k]) * hat_f(i, s[e], a, b) * hat_f(j, s[k], a, b) \
for e in range(len(s))]) for k in range(len(s))]) for j in range(len(t))])
return np.array(A)
def solve_c(A, f):
return np.linalg.solve(A, f) # linalg.solve(a, b) 求解线性矩阵方程或线性标量方程组。
def solve_xn(c, a, b, n):
h = (b - a) / (n)
t = [a + i * h for i in range(0, n + 1)] # 等距划分a=t0<t1<...<tn=b
xn = [sum([c[j] * hat_f(j, i, a, b) for j in range(len(t))]) for i in t]
t = np.array(t) # 进行数据格式转化,加入‘x’为list类型,将其转换成数组的代码:
error = function_x(t) - xn
# print(LA.norm(error,np.inf))
plt.scatter(t, xn, marker='x', color='r')
return xn, LA.norm(error, np.inf)
if __name__ == '__main__':
print('******************************程序入口*******************************')
lamda = 1
n = 8
a = 0
b = 1
m = 400
print('calculating...')
x, w = gauss_xw(m)
f = gauss_solve_f(x, w, lamda, a, b, n)
A = elements_of_matrix(x, w, a, b, lamda, n)
c = solve_c(A, f)
xn, error = solve_xn(c, a, b, n)
l = len(xn)
print(xn[l - 1])
print('the error is:', error)
# print('all_cost_time:', time.time() - start_time)
plt.xlabel('t')
plt.ylabel('xn')
plt.show()
print('success')
def show():
s = sy.symbols('s')
t = sy.symbols('t')
K2 = entry3.get()
f2 = entry4.get()
K1 = entry.get()
x1 = entry2.get()
tmptext1 = "Fredholm II:"+"$x(t)-\int_{0}^{1}" + str(sy.latex(eval(functionformate(K1)))) +"x(s)ds"+ "="+str(sy.latex(eval(functionformate(x1)))) + "$"
tmptext2 = "Fredholm I:"+"$\int_{-1}^{1}" + str(sy.latex(eval(functionformate(K2)))) +"y(t)dt ="+ str(sy.latex(eval(functionformate(f2)))) + "$"
wx.clear()
wx.text(0, 0.8, tmptext1, fontsize=20)
wx.text(0, 0.2, tmptext2, fontsize=20)
canvas.draw()
tk.Button(win4, text='Start Fredholm I', command=start1).pack()
tk.Button(win4, text='Start Fredholm II', command=start2).pack()
tk.Button(win4, text='Show math formula', command=show).pack()
# 第5步,创建一个菜单栏,这里我们可以把他理解成一个容器,在窗口的上方
#Создайте меню, где мы можем понять его как контейнер, который находится над окном
menubar = tk.Menu(window)
# 第6步,创建一个File菜单项(默认不下拉,下拉内容包括New,Open,Save,Exit功能项)
filemenu = tk.Menu(menubar, tearoff=0)
# 将上面定义的空菜单命名为File,放在菜单栏中,就是装入那个容器中
menubar.add_cascade(label='Functionality', menu=filemenu)
# 在File中加入New、Open、Save等小菜单,即我们平时看到的下拉菜单,每一个小菜单对应命令操作。
filemenu.add_command(label='No.1', command=no1)
filemenu.add_command(label='No.2', command=no2)
filemenu.add_command(label='No.3', command=no3)
filemenu.add_command(label='No.4', command=no4)
filemenu.add_separator() # 添加一条分隔线
filemenu.add_command(label='Exit', command=window.quit) # 用tkinter里面自带的quit()函数
# 第11步,创建菜单栏完成后,配置让菜单栏menubar显示出来
#После создания меню Настройка Показать меню меню
window.config(menu=menubar)
# 第12步,主窗口循环显示
window.mainloop()