user3656142
user3656142

Reputation: 467

Why is numpy.trapz() returning zero?

I have the following setup:

a.T = [[0.  0.4 0.8 1.2 1.6 1.  1.2 1.4 1.6 1.8 0.5 0.9 1.3 1.7 2.1 2. ]]
b.T = [[0.  0.4 0.8 1.2 1.6 2.  2.2 2.4 2.6 2.8 3.  3.4 3.8 4.2 4.6 5. ]]

Consider b as being the time values and the values taken by a function at those instants is given by a.

Now when I do np.trapz(interpolated_age,interpolated_time), I get the result of this integral operation as multiple 0 valued arrays. But if I do the transpose operation to the arguments of the trapz method, i.e. np.trapz(interpolated_age.T,interpolated_time.T), I get the correct answer as a single value.

Can someone point out what's the reason behind this? I thought for trapz operation, we only need 2 same sized arrays for the 2D integration.

Upvotes: 1

Views: 1461

Answers (1)

Stef
Stef

Reputation: 30579

Your arrays interpolated_age and interpolated_time are of shape(n,1). trapz has an axis parameter with default -1 (last axis). That means that you calculate n times the area under a single point which is 0, hence you get an array of n zeros.

If you need your array to be 2D then specify axis=0 to integrate over the first axis (n points) to get the correct result.

area_under_curve = np.trapz(interpolated_age, interpolated_time, axis=0)

Alternatively, you may check if you could use simple 1D arrays (can't tell from your program code).

Upvotes: 1

Related Questions