3

Initially, I have two arrays that correspond to the values of x and y in a function, but I don't know that function, I just know that the values of y depend on x. Then, I calculate a function that depends on both arrays.

I need to calculate in python the integral of that last function to obtain the total area under the curve between the first value of x and the last. Any idea of how to do that?

x = [array]
y(x) = [array]

a = 2.839*10**25
b = 4*math.pi
alpha = 0.5
z = 0.003642
def L(x,y,a,b,alpha,z):
    return x*((y*b*a)/(1+z)**(1+alpha))

  • So basically you need to integrate function `L(x,y)` over `x`? – AnsFourtyTwo May 25 '20 at 14:45
  • If your `x`-values are equally spaced, you can use the Simpson's rule provided in [scipy.integrate.simps](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html). – AnsFourtyTwo May 25 '20 at 14:51
  • Yes, that's what I need, integrate L over x, but since y depends also on x, I haven't been able to do it with quad. And no, x values are not equally space. – Silvia Rueda May 25 '20 at 17:11

1 Answers1

0

Your function is a function of x (in that given a value of x it spits out a value), so first you should repackage it as such (introduce a function yy which, given x, produces the requisite y), then write LL(x) = L(x, yy[x]), then use scipy.integrate to integrate it.

Igor Rivin
  • 4,632
  • 2
  • 23
  • 35
  • That's the problem. Because initially I can't write y as a function of x, I just know that y depends on x, but not in a known function, I just have the arrays for both variables. This is a spectrum, so y is a flux, and x is wavelength. – Silvia Rueda May 25 '20 at 17:14
  • @SilviaRueda make a dictionary thus: `dict = [] for i in range(len(x))) dict[x[i]]=y[i]` then define a function by `yy(x) = dict[x]` – Igor Rivin May 25 '20 at 17:26
  • When making the dictionary I'm getting this error: TypeError: list indices must be integers or slices, not numpy.float64 I think this is because it's not iterating through an element on the array and not an index, so I'm not sure how to fix it – Silvia Rueda May 25 '20 at 18:05
  • @SilviaRueda Use this solution: https://stackoverflow.com/questions/23721230/float-values-as-dictionary-key – Igor Rivin May 25 '20 at 18:11
  • You mean doing this? dict = [ ] for i in range(len(wl)): dict[round(wl[i],4)]=round(fl[i],4) where wl is x and fl is y. Because it keeps showing the same error – Silvia Rueda May 25 '20 at 18:24