Animesh Pandey
Animesh Pandey

Reputation: 6018

Finding zero crossings from a list in python

I did write a code for doing this:

for i in xrange(len(Derivative)):
    if ((Derivative[i-1] > Derivative[i]) and (Derivative[i+1] < Derivative[i]) and (Derivative[i-1] > 0.0) and (Derivative[i+1] < 0.0) and (Derivative[i] > 0.0)):
        print str(i+1)

Here Derivative is list in which I have to detect zero crossing mainly the ones where the values just before zero crossing is positive and one after zero crossing to be negative.

I have attached the graph of Derivative to further elucidate the problem!

I wish to know if there is better way of doing this in Python, I mean shorter and precise code ?

Upvotes: 0

Views: 7292

Answers (1)

Kevin
Kevin

Reputation: 76234

You only need to compare the current derivative with the one following it. As a result, you can delete any references to Derivative[i-1]. If Derivative[i] is greater than zero, and Derivative[i+1] is less than zero, then necessarily Derivative[i+1] < Derivative[i]. So you can delete that condition as well. This leaves:

for i in xrange(len(Derivative)-1):
    if Derivative[i] > 0 and Derivative[i+1] < 0:
        print "crossing between indexes {} and {}".format(i, i+1)

Also, I shortened the argument to xrange by one. Otherwise, you'd get list index out of range.

Upvotes: 1

Related Questions