簡體   English   中英

計算曲線下面積時面積的負值

[英]Negative Values of Area when calculating area Under a Curve

我在python中使用polyval獲得了多項式的系數。 我使用以下代碼來計算多項式的面積。 可視化時,曲線出現在 y=0 線上方。 但是計算出來的面積似乎是負的。 您能否請人幫助我以下代碼有什么問題。

import numpy as np
# insert the coefficents of the polynomial
p = np.array([ 2.60349395e+09, -3.34913329e+10,  1.87588633e+11, -5.85791667e+11,
           1.04784500e+12, -8.03652884e+11, -8.37573977e+11,  3.17205629e+12,
           -4.33851893e+12,  3.48269443e+12, -1.71966834e+12,  4.86703099e+11,
           -6.07938187e+10])

def f(x):
    return ((p[0]*(x**12))+(p[1]*(x**11))+(p[2]*(x**10)))+(p[3]*(x**9))+(p[4]*(x**8))+
            (p[5]*(x**7))+(p[6]*(x**6))+(p[7]*(x**5))+(p[8]*(x**4))+(p[9]*(x**3))+
            (p[10]*(x**2))+(p[11]*(x**1))+(p[12]))

N = 1000
#insert the initial value of independent variable
x1=1
#insert the final value of the independent variable
x2 = 1.578687

dx = (x2 - x1)/N

A = 0
t=x1

while t<=x2:
  dA=f(t)*dx
  A = A +dA
  t = t + dx

# Area under the curve
print("A=",A)

面積為負,因為函數f(t)在該區間內嚴格為負。 您可以通過使用np.arangematplotlib包快速繪制函數來看到這一點。

import numpy as np
import matplotlib.pyplot as plt
# insert the coefficents of the polynomial
p = np.array([ 2.60349395e+09, -3.34913329e+10,  1.87588633e+11, -5.85791667e+11,
          1.04784500e+12, -8.03652884e+11, -8.37573977e+11,  3.17205629e+12,
          -4.33851893e+12,  3.48269443e+12, -1.71966834e+12,  4.86703099e+11,
          -6.07938187e+10])

def f(x):
   return (p[0]*(x**12) + p[1]*(x**11) + p[2]*(x**10)+ p[3]*(x**9) + p[4]*(x**8) +
           p[5]*(x**7) + p[6]*(x**6) + p[7]*(x**5) + p[8]*(x**4) + p[9]*(x**3) +
           p[10]*(x**2) + p[11]*x+p[12])

plt.plot(np.arange(0, 2, 0.001), f(np.arange(0, 2,  0.001))) # plotting

在此處輸入圖片說明

您還可以在積分時使用異常來檢查f(t)負值:

N = 1000
#insert the initial value of independent variable
x1 = 1
#insert the final value of the independent variable
x2 = 1.578687

dx = (x2 - x1)/N

A = 0
t = x1

while t<=x2:
    if f(t) < 0:
        # raise exception if negative value is encountered, integration will stop.
        raise Exception("Negative values encountered") 
    else:
        dA = f(t)*dx
        A = A +dA
        t = t + dx
        


# Area under the curve
print("A=",A)

輸出:

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-38-2aea71dc1318> in <module>
     12 while t<=x2:
     13     if f(t) < 0:
---> 14         raise Exception("Negative values encountered")
     15     else:
     16         dA = f(t)*dx

Exception: Negative values encountered

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM