Search code examples
pythonpython-3.xcalculusdifferentiation

Range Function For Floats In Small Intervals


I want to find the derivative of a function (x)(x - 1) using the definition of a derivative. I want my increments to be 1e-2. So that it simulates the limit going to zero. I saw on Range for Floats that I could use user-defined functions to create range functions that take float variables.

def frange(x, y, jump):
    while x < y:
        yield x
        x += jump

    def drange(start, stop, step):
     r = start
     while r < stop:
        yield r
        r += step

i = frange(1e-14,1e-2,2)

for k in i:
    set  = []
    x = 1
    dvt = ((x + k ) * (x + k - 1) - x*(x - 1))/k

    set.append(dvt)
    print(set)

When I run the program I only get

[0.9992007221626509]

What is going on that I am not getting more than one derivative added to the list?


Solution

  • set You are saying

    x += jump
    

    This sets the value of x to 2 + 1e-14 which is greater than 1e-2

    As I read the code, it seems that you may mean

    myjump = pow(10, jump) #outside the loop
    
    x *= myjump # inside the loop
    

    This will multiply each loop through by 100 in the example and process 1e-14, 1e-12, 1e-10 ... 1e-2

    Alternatively, if you meant to add it, then you should have said

    x += myjump # inside the loop
    

    or you need to test that jump is actually a fraction that is small enough to be processed.