All problems
Complex-Step Derivative
Problem
The complex-step derivative avoids subtractive cancellation entirely:
f'(x) = Im(f(x + i*h)) / h
Using h = 1e-20 gives near machine precision. Apply this to the polynomial f(x) = sum(coeffs[i] * x^i) and return the derivative estimate.
Hint
The imaginary part of a complex evaluation carries the derivative with no cancellation error.
Test cases
case 1
in: [[0,0,1],3]
expected: 6
case 2
in: [[0,2,0,1],2]
expected: 13.999999999999998
case 3
in: [[5],1]
expected: 0
case 4
in: [[0,1],1]
expected: 1
Starter codePython
def complex_step_derivative(coeffs, x, h=1e-20):
# Your code here
pass4 test cases · run your code against them in the editor