当前位置:首页 » 编程语言 » 用python科学计算

用python科学计算

发布时间: 2022-10-03 11:00:02

‘壹’ 为什么用python进行科学计算

不得不说这是一个形势所趋,
现在高校的很多老师,及学生做科学计算相关的项目都是python。原因大约有以下几点:
Python的语法简单,这对很少接触编程的搞学术老师的福音。
Python相较于其他语言有更丰富的模块,比如科学计算的numpy。
Python越来越流行。

‘贰’ python高级科学计算和python科学计算区别

等级和效果。
1、等级:python高级科学计算指的是高级的科学计算过程方式,而python科学计算指的是普通的计算的方式。
2、效果:python高级科学计算可以达到减少内存占用,随时生产,即时消费,不用堆积在内存当中。而python科学计算达不到这个效果。

‘叁’ 如何用 Python 科学计算中的矩阵替代循环

import time
import math
import numpy as np

x = [i * 0.001 for i in xrange(1000000)] # 初始化数组0.000~999.999
start = time.clock()
for i, t in enumerate(x): # 用循环计算正弦值
x[i] = math.sin(t)
print "math.sin:", time.clock() - start

x = [i * 0.001 for i in xrange(1000000)]
x = np.array(x) # 初始化矩阵(这里是一维)
start = time.clock()
np.sin(x,x) # numpy的广播计算(代替循环)
print "numpy.sin:", time.clock() - start

# 输出
# math.sin: 1.15426932753
# numpy.sin: 0.0882399858083

‘肆’ 如何用 Python 写一个带 GUI 的科学计算程序

使用Tkinter图形库,如果你是用的linux系统 记得将第一行改为from tkinter import *
这个代码实现的挺简单,并不是很复杂的科学计算器界面,你可以以此为基础,添加自己想要的东西:给你个截图:
代码是如下, 我就不给你添注释了啊:
#!/usr/bin/env python3.4
from Tkinter import *
import parser
root = Tk()
root.title('Calculator')
i = 0
def factorial():
"""Calculates the factorial of the number entered."""
whole_string = display.get()
number = int(whole_string)
fact = 1
counter = number
try:
while counter > 0:
fact = fact*counter
counter -= 1
clear_all()
display.insert(0, fact)
except Exception:
clear_all()
display.insert(0, "Error")
def clear_all():
"""clears all the content in the Entry widget"""
display.delete(0, END)
def get_variables(num):
"""Gets the user input for operands and puts it inside the entry widget"""
global i
display.insert(i, num)
i += 1
def get_operation(operator):
"""Gets the operand the user wants to apply on the functions"""
global i
length = len(operator)
display.insert(i, operator)
i += length
def undo():
"""removes the last entered operator/variable from entry widget"""
whole_string = display.get()
if len(whole_string): ## repeats until
## now just decrement the string by one index
new_string = whole_string[:-1]
print(new_string)
clear_all()
display.insert(0, new_string)
else:
clear_all()
display.insert(0, "Error, press AC")
def calculate():
"""
Evaluates the expression
ref : http://stackoverflow.com/questions/594266/equation-parsing-in-python
"""
whole_string = display.get()
try:
formulae = parser.expr(whole_string).compile()
result = eval(formulae)
clear_all()
display.insert(0, result)
except Exception:
clear_all()
display.insert(0, "Error!")
root.columnconfigure(0,pad=3)
root.columnconfigure(1,pad=3)
root.columnconfigure(2,pad=3)
root.columnconfigure(3,pad=3)
root.columnconfigure(4,pad=3)
root.rowconfigure(0,pad=3)
root.rowconfigure(1,pad=3)
root.rowconfigure(2,pad=3)
root.rowconfigure(3,pad=3)
display = Entry(root, font = ("Calibri", 13))
display.grid(row = 1, columnspan = 6 , sticky = W+E)
one = Button(root, text = "1", command = lambda : get_variables(1), font=("Calibri", 12))
one.grid(row = 2, column = 0)
two = Button(root, text = "2", command = lambda : get_variables(2), font=("Calibri", 12))
two.grid(row = 2, column = 1)
three = Button(root, text = "3", command = lambda : get_variables(3), font=("Calibri", 12))
three.grid(row = 2, column = 2)
four = Button(root, text = "4", command = lambda : get_variables(4), font=("Calibri", 12))
four.grid(row = 3 , column = 0)
five = Button(root, text = "5", command = lambda : get_variables(5), font=("Calibri", 12))
five.grid(row = 3, column = 1)
six = Button(root, text = "6", command = lambda : get_variables(6), font=("Calibri", 12))
six.grid(row = 3, column = 2)
seven = Button(root, text = "7", command = lambda : get_variables(7), font=("Calibri", 12))
seven.grid(row = 4, column = 0)
eight = Button(root, text = "8", command = lambda : get_variables(8), font=("Calibri", 12))
eight.grid(row = 4, column = 1)
nine = Button(root , text = "9", command = lambda : get_variables(9), font=("Calibri", 12))
nine.grid(row = 4, column = 2)
cls = Button(root, text = "AC", command = clear_all, font=("Calibri", 12), foreground = "red")
cls.grid(row = 5, column = 0)
zero = Button(root, text = "0", command = lambda : get_variables(0), font=("Calibri", 12))
zero.grid(row = 5, column = 1)
result = Button(root, text = "=", command = calculate, font=("Calibri", 12), foreground = "red")
result.grid(row = 5, column = 2)
plus = Button(root, text = "+", command = lambda : get_operation("+"), font=("Calibri", 12))
plus.grid(row = 2, column = 3)
minus = Button(root, text = "-", command = lambda : get_operation("-"), font=("Calibri", 12))
minus.grid(row = 3, column = 3)
multiply = Button(root,text = "*", command = lambda : get_operation("*"), font=("Calibri", 12))
multiply.grid(row = 4, column = 3)
divide = Button(root, text = "/", command = lambda : get_operation("/"), font=("Calibri", 12))
divide.grid(row = 5, column = 3)
# adding new operations
pi = Button(root, text = "pi", command = lambda: get_operation("*3.14"), font =("Calibri", 12))
pi.grid(row = 2, column = 4)
molo = Button(root, text = "%", command = lambda : get_operation("%"), font=("Calibri", 12))
molo.grid(row = 3, column = 4)
left_bracket = Button(root, text = "(", command = lambda: get_operation("("), font =("Calibri", 12))
left_bracket.grid(row = 4, column = 4)
exp = Button(root, text = "exp", command = lambda: get_operation("**"), font = ("Calibri", 10))
exp.grid(row = 5, column = 4)
## To be added :
# sin, cos, log, ln
undo_button = Button(root, text = "<-", command = undo, font =("Calibri", 12), foreground = "red")
undo_button.grid(row = 2, column = 5)
fact = Button(root, text = "x!", command = factorial, font=("Calibri", 12))
fact.grid(row = 3, column = 5)
right_bracket = Button(root, text = ")", command = lambda: get_operation(")"), font =("Calibri", 12))
right_bracket.grid(row = 4, column = 5)
square = Button(root, text = "^2", command = lambda: get_operation("**2"), font = ("Calibri", 10))
square.grid(row = 5, column = 5)
root.mainloop()

‘伍’ 如何用 Python 写一个带 GUI 的科学计算程序

强烈推荐使用Tk 库,非常简单。 下面是我正在写的界面,可以运行,后台还没处理好。不懂的可以问我。

#!python2pymol
#coding:utf-8


fromTkinterimport*
fromttkimport*
frommathimportsin,asin,cos,acos

classPredictGui(Frame):
def__init__(self,parent=None):
Frame.__init__(self,parent)
self.pack(expand=YES,fill=BOTH)

Label(self,text="generatecccc").pack(side=TOP)

centerF=Frame(self)
centerF.pack(expand=YES,fill=BOTH)
Label(centerF,width=50,text="thecoordofthecenter").pack(side=LEFT)
self.xyz_var=StringVar()
Entry(centerF,text=self.xyz_var,width=15).pack(side=LEFT)
self.xyz_var.set('000')


radiusF=Frame(self)
radiusF.pack(side=TOP,fill=BOTH,expand=YES)
Label(radiusF,text="theradiusofthecc",width=50).pack(side=LEFT)
self.r_var=DoubleVar()
radius_Com=Combobox(radiusF,width=15,textvariable=self.r_var)
radius_Com.pack(side=LEFT)
radius_Com['values']=(5.0,10.0,15.0,20.0,)
radius_Com.set('selectradius')
radius_Com.bind("<<ComboboxSelected>>",self.selectradius)


densityF=Frame(self)
densityF.pack(expand=YES,fill=BOTH)
Label(densityF,text="thedensityis0-1",width=50).pack(side=LEFT)
self.density_var=DoubleVar()
Entry(densityF,text=self.density_var,width=15).pack(side=LEFT)defselectradius(event,self):
'''
'''
temp=asin(1.0/self.r_var.get())
self.density_var.set(temp)if__name__=='__main__':
mainW=PredictGui()
mainW.mainloop()

‘陆’ 什么是Python科学计算

本书介绍如何用Python开发科学计算的应用程序,除了介绍数值计算之外,还着重介绍如何制作交互式的2D、3D图像,如何设计精巧的程序界面,如何与C语言编写的高速计算程序结合,如何编写声音、图像处理算法等内容。书中涉及的Python扩展库包括NumPy、SciPy、SymPy、matplotlib、Traits、TraitsUI、Chaco、TVTK、Mayavi、VPython、OpenCV等,涉及的应用领域包括数值运算、符号运算、二维图表、三维数据可视化、三维动画演示、图像处理以及界面设计等。书中以大量实例引导读者逐步深入学习,每个实例程序都有详尽的解释,并都能在本书推荐的运行环境中正常运行。此外,本书附有大量的图表和插图,力求减少长篇的理论介绍和公式推导,以便读者通过实例和数据学习并掌握理论知识。

‘柒’ python能做什么

python可以做:

1、Web开发;

2、数据科学研究;

3、网络爬虫;

4、嵌入式应用开发;

5、游戏开发;

6、桌面应用开发。

Python解释器易于扩展,可以使用C或C++(或者其他可以通过C调用的语言)扩展新的功能和数据类型。Python 也可用于可定制化软件中的扩展程序语言。Python丰富的标准库,提供了适用于各个主要系统平台的源码或机器码。

(7)用python科学计算扩展阅读

由于Python语言的简洁性、易读性以及可扩展性,在国外用Python做科学计算的研究机构日益增多,一些知名大学已经采用Python来教授程序设计课程。例如卡耐基梅隆大学的编程基础、麻省理工学院的计算机科学及编程导论就使用Python语言讲授。

众多开源的科学计算软件包都提供了Python的调用接口,例如着名的计算机视觉库OpenCV、三维可视化库VTK、医学图像处理库ITK。

参考资料来源:网络-Python

‘捌’ 如何使用python计算常微分方程

常用形式
odeint(func, y0, t,args,Dfun)
一般这种形式就够用了。
下面是官方的例子,求解的是
D(D(y1))-t*y1=0
为了方便,采取D=d/dt。如果我们令初值
y1(0) = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)
D(y1)(0) = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)
这个微分方程的解y1=airy(t)。

令D(y1)=y0,就有这个常微分方程组。
D(y0)=t*y1
D(y1)=y0

Python求解该微分方程。
>>> from scipy.integrate import odeint
>>> from scipy.special import gamma, airy
>>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)
>>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)
>>> y0 = [y0_0, y1_0]
>>> def func(y, t):
... return [t*y[1],y[0]]
>>> def gradient(y,t):
... return [[0,t],[1,0]]
>>> x = arange(0,4.0, 0.01)
>>> t = x
>>> ychk = airy(x)[0]
>>> y = odeint(func, y0, t)
>>> y2 = odeint(func, y0, t, Dfun=gradient)
>>> print ychk[:36:6]
[ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806]
>>> print y[:36:6,1]
[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806]
>>> print y2[:36:6,1]
[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806]

得到的解与精确值相比,误差相当小。
=======================================================================================================

args是额外的参数。
用法请参看下面的例子。这是一个洛仑兹曲线的求解,并且用matplotlib绘出空间曲线图。(来自《python科学计算》)
from scipy.integrate import odeint
import numpy as np
def lorenz(w, t, p, r, b):
# 给出位置矢量w,和三个参数p, r, b 计算出
# dx/dt, dy/dt, dz/dt 的值
x, y, z = w
# 直接与lorenz 的计算公式对应
return np.array([p*(y-x), x*(r-z)-y, x*y-b*z])
t = np.arange(0, 30, 0.01) # 创建时间点
# 调用ode 对lorenz 进行求解, 用两个不同的初始值
track1 = odeint(lorenz, (0.0, 1.00, 0.0), t, args=(10.0, 28.0, 3.0))
track2 = odeint(lorenz, (0.0, 1.01, 0.0), t, args=(10.0, 28.0, 3.0))
# 绘图
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(track1[:,0], track1[:,1], track1[:,2])
ax.plot(track2[:,0], track2[:,1], track2[:,2])
plt.show()
===========================================================================
scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)
计算常微分方程(组)
使用 FORTRAN库odepack中的lsoda解常微分方程。这个函数一般求解初值问题。

参数:

func : callable(y, t0, ...) 计算y在t0 处的导数。
y0 : 数组 y的初值条件(可以是矢量)
t : 数组 为求出y,这是一个时间点的序列。初值点应该是这个序列的第一个元素。
args : 元组 func的额外参数
Dfun : callable(y, t0, ...) 函数的梯度(Jacobian)。即雅可比多项式。
col_deriv : boolean. True,Dfun定义列向导数(更快),否则Dfun会定义横排导数
full_output : boolean 可选输出,如果为True 则返回一个字典,作为第二输出。
printmessg : boolean 是否打印convergence 消息。

返回: y : array, shape (len(y0), len(t))
数组,包含y值,每一个对应于时间序列中的t。初值y0 在第一排。
infodict : 字典,只有full_output == True 时,才会返回。
字典包含额为的输出信息。
键值:

‘hu’ vector of step sizes successfully used for each time step.
‘tcur’ vector with the value of t reached for each time step. (will always be at least as large as the input times).
‘tolsf’ vector of tolerance scale factors, greater than 1.0, computed when a request for too much accuracy was detected.
‘tsw’ value of t at the time of the last method switch (given for each time step)
‘nst’ cumulative number of time steps
‘nfe’ cumulative number of function evaluations for each time step
‘nje’ cumulative number of jacobian evaluations for each time step
‘nqu’ a vector of method orders for each successful step.
‘imxer’index of the component of largest magnitude in the weighted local error vector (e / ewt) on an error return, -1 otherwise.
‘lenrw’ the length of the double work array required.
‘leniw’ the length of integer work array required.
‘mused’a vector of method indicators for each successful time step: 1: adams (nonstiff), 2: bdf (stiff)
其他参数,官方网站和文档都没有明确说明。相关的资料,暂时也找不到。

‘玖’ python的科学计算库有哪些

1、Numpy库简介
在Python中很多高级库都是基本Numpy科学库去做的。之前如果用Python对数据进行操作,需要一行一行或者一个一个数据的去进行操作。而在Numpy中,则是封装了一系列矩阵的操作:首先把数据转换成一系列矩阵的格式,然后再对矩阵进行操作。这样既高效,也省时。Numpy封装了一系列的函数函数,方便我们去操作矩阵。Numpy中一行代码就顶Python中十几行的代码。
2、Pandas库简介
在Pandas 是基于Numpy的一种工具,该工具是为了解决数据分析任务而创建的。Pandas
纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。Pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。
3、Matplotlib库简介
Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形,通过
Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

‘拾’ 用python计算圆的面积

首先定义一个findArea()方法,参数r为圆的半径,圆周率π取3.142,函数的返回值为PI * (r*r),然后调用该方法即可求出圆的面积。

Python解释器易于扩展,可以使用C或C++(或者其他可以通过C调用的语言)扩展新的功能和数据类型。[4]Python 也可用于可定制化软件中的扩展程序语言。Python丰富的标准库,提供了适用于各个主要系统平台的源码或机器码。

2021年10月,语言流行指数的编译器Tiobe将Python加冕为最受欢迎的编程语言,20年来首次将其置于Java、C和JavaScript之上。

由于Python语言的简洁性、易读性以及可扩展性,在国外用Python做科学计算的研究机构日益增多,一些知名大学已经采用Python来教授程序设计课程。例如卡耐基梅隆大学的编程基础、麻省理工学院的计算机科学及编程导论就使用Python语言讲授。

众多开源的科学计算软件包都提供了Python的调用接口,例如着名的计算机视觉库OpenCV、三维可视化库VTK、医学图像处理库ITK。而Python专用的科学计算扩展库就更多了。

热点内容
如何获得打印机无线密码 发布:2024-05-04 06:44:59 浏览:416
上古诸神录哪里改密码 发布:2024-05-04 06:43:55 浏览:261
灌篮高手手游自动盖帽脚本 发布:2024-05-04 06:42:31 浏览:423
javajs引擎 发布:2024-05-04 06:37:33 浏览:796
javalist重复 发布:2024-05-04 06:19:27 浏览:509
max脚本管理 发布:2024-05-04 06:02:31 浏览:45
自行搭建服务器 发布:2024-05-04 06:01:12 浏览:125
h3c如何查看所有配置 发布:2024-05-04 05:26:39 浏览:493
java统计字符串中字母个数 发布:2024-05-04 05:22:58 浏览:888
throwablejava 发布:2024-05-04 05:22:56 浏览:792