[python]TypeError: only size-1 arrays can be converted to Python scalars

当在代码中同时import numpy库和math库时,在进行sin、exp等运算时需要使用 np.exp()或者 np.sin(),否则就会报这个错误。

# -*- coding: utf-8 -*-
"""
Created on Wed Mar  9 19:45:00 2022

@author: REESE
"""
from math import *
import numpy as np
def f(x):
    return np.exp(-x**2)*np.sin(10*x)
def trapezoidal1(f,a,x,n):
    h = (x-a)/n
    I = 0.5*f(a)
    for i in range(1,n):
        I += f(a + i*h)
    I += 0.5*f(x)
    I *= h
    return I
def trapezoidal2(f,a,x,n):
    h = (x - a) / n
    y = f((np.linspace(a, x, (n + 1))))
    y1 = y[:-1]  # 除去最后一个元素的list
    y2 = y[1:]  # 除去第一个元素的list
    return sum(0.5 * h * (y1 + y2))  # y1+y2相当于两个list各项相加,得到一个新的list。各个梯形的和

class Intergral:
    def __init__(self, f, a, n = 100):
        self.f,self.a,self.n = f,a,n
    def __call__(self, x):
        f,a,n = self.f, self.a, self.n
        #return trapezoidal1(f,a,x,n)
        return trapezoidal2(f,a,x,n)

a = 0; n = 200
x = 1
F = Intergral(lambda x: 1+x-x, a, n)
print(F(x)) #test: must about 1
x = 1.2
F = Intergral(f,a,n)
print(F(x))

改动就是在f(x)内加了两个np.
需要注意的是:该代码运行并不需要math库。如果不import math的话就不会出现问题了。故:养成良好习惯,少写无用代码~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值