[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的话就不会出现问题了。故:养成良好习惯,少写无用代码~

你可能感兴趣的:(python,python,pycharm,开发语言)