scipy

作者: 陈文瑜 | 来源:发表于2019-10-02 08:36 被阅读0次

    SciPy求函数的积分

    • 单积分 \int _a^b f(x)dx \quad f(x) = e^{-x^2}
    import scipy.integrate
    from numpy import exp
    f= lambda x:exp(-x**2)
    i = scipy.integrate.quad(f, 0, 1)
    print (i)
    
    • 双重积分 \int _0^{\frac12} dy \int _0^{\sqrt{1-4y^2}}16xydx
    import scipy.integrate
    from numpy import exp
    from math import sqrt
    f = lambda x, y : 16*x*y
    g = lambda x : 0
    h = lambda y : sqrt(1-4*y**2)
    i = scipy.integrate.dblquad(f, 0, 0.5, g, h)
    print (i)
    

    多项式函数 poly1d

    • 表达式
      f(x) = a_nx^n +a_{n-1}x^{n-1}+···+a_2x^2+a_1x+a_0

    • 举例多项式 f(x) = x^3 -2x +1
      多项式的系数可以表示为数组:

      a = np.array([1.0,0,-2,1])  # 其中 a[0] 是最高次项,a[-1] 是常数项。
      

      多项式可以表示为

      p = np.poly1d(a)
      

      代入变量可得结果

      p(np.linspace(0,1,5)) # 输出 array([ 1. ,  0.515625,  0.125   , -0.078125,  0.  ])
      

    leastsq最小二乘法

    • 理解
      找出一组\theta使得某残差平方和最小
    • 代码示例
      # 目标函数
      def real_func(x):
          return np.sin(2*np.pi*x)
      # 多项式
      def fit_func(p, x):
          f = np.poly1d(p)
          return f(x)
      # 残差
      def residuals_func(p, x, y):
          ret = fit_func(p, x) - y
          return ret
      
      x = np.linspace(0, 1, 10)
      y_ = real_func(x)
      y = [np.random.normal(0, 0.1)+y1 for y1 in y_]
      # 随机初始化多项式参数
      p_init = np.random.rand(M+1)
      # 最小二乘法
      p_lsq = leastsq(residuals_func, p_init, args=(x, y))
      

    相关文章

      网友评论

          本文标题:scipy

          本文链接:https://www.haomeiwen.com/subject/gobkpctx.html