python用quad、dblquad实现一维二维积分的实例详解

yipeiwu_com6年前Python基础

背景:

python函数库scipy的quad、dblquad实现一维二维积分的范例。需要注意dblquad的积分顺序问题。

代码:

import numpy as np
from scipy import integrate
 
 
def half_circle(x):
  """
  原心:(1,0),半径为1
  半圆函数:(x-1)^2+y^2 = 1
  """
  return (1-(x-1)**2)**0.5
 
"""
梯形法求积分:半圆线和x轴包围的面积
"""
N = 10000
x = np.linspace(0,2,num=N)#,endpoint=True)
dh = (2-0)/N
y = half_circle(x)
"""
梯形法求积分:(上底+ 下底)*高/2
"""
S = sum((y[1:]+y[:-1])*dh/2)
 
print("=========%s=========="%"梯形法")
print("面积:%f"%S)
 
"""
直接调用intergrate的积分函数quad
"""
S2,err = integrate.quad(half_circle,0,2)
 
print("=========%s=========="%"quad")
print("面积:%f"%S2)
 
 
"""
多重定积分:注意积分顺序
"""
def half_sphere(y,x):
  """
  球心:(1,0,0)
  半径:1
  半球:(x-1)^2+y^2+z^2=1
  """
  return (1-(x-1)**2-y**2)**0.5
 
"""
积分顺序:
v = V x in [0,2] :V y in [-g(x),h(x)]
"""
V3,err = integrate.dblquad(half_sphere,0,2,lambda x:-half_circle(x),lambda x:half_circle(x))
print("========%s==========="%"dblquad")
print("体积:%f"%V3)

结果:

========
=========梯形法==========
面积:1.570638
=========quad==========
面积:1.570796
========dblquad===========
体积:2.094395

以上这篇python用quad、dblquad实现一维二维积分的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3 pandas 读取MySQL数据和插入的实例

python 代码如下: # -*- coding:utf-8 -*- import pandas as pd import pymysql import sys from sqla...

多版本python的pip 升级后, pip2 pip3 与python版本失配解决方法

多版本python的pip 升级后, pip2 pip3 与python版本失配解决方法

mint19.2   本来pip 和 pip2 对应 python2.7   pip3对应python3.6   用源码安装了...

使用Python爬了4400条淘宝商品数据,竟发现了这些“潜规则”

使用Python爬了4400条淘宝商品数据,竟发现了这些“潜规则”

本文记录了笔者用 Python 爬取淘宝某商品的全过程,并对商品数据进行了挖掘与分析,最终得出结论。 项目内容 本案例选择>> 商品类目:沙发; 数量:共100页 ...

python如果快速判断数字奇数偶数

这篇文章主要介绍了python如果快速判断数字奇数偶数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用 按位与运算符(&) 将能更...

关于Python中异常(Exception)的汇总

前言 Exception类是常用的异常类,该类包括StandardError,StopIteration, GeneratorExit, Warning等异常类。python中的异常使用...