javascriptpythonmathpolynomial-mathcalculus

# Find the tangent of any polynomial function at x

Problem:

I'm looking for a catch-all function that I can use to calculate the tangent of any polynomial function at x. I'm indifferent to the language used although JavaScript or Python would be prefered! I should be able to pass in any x value and an array of coefficients in the format, a + bx + cx^2 + dx^3 ... and so on.

Example function format:

``````function findTangent(x, coefficients) {

// Do differential calculus here.

return [tangentIntercept, tangentSlope]

}
``````

Example function test:

Say I have the function, y = 2 + 7x + 5x^2 + x^3 and I want to to find the tangent at, x = -2. I could call this function like so, `findTangent(-2, [2, 7, 5, 1])` and get a return value like this, `[-2, -1]` representing the tangent, y = -2 - x.

Notes:

I have looked for an answer on the Math Stackexchange and Google search but all the results are in a mathematical syntax and not code. I want a programmatic solution, I am far more comfortable with loops and if statements than funny symbols and math jargon!

Solution

• Okay so after a day of struggling with it I think I have got the solution in both JavaScript and Python!

The JavaScript Solution:

``````function findTangent(x, coefficients) {

let slope = 0
let intercept = coefficients[0]

for (let i = 1; i < coefficients.length; i++) {

slope += coefficients[i] * i * Math.pow(x, i - 1)
intercept += coefficients[i] * Math.pow(x, i)

}

return [intercept - slope * x, slope]

}
``````

The Python Solution:

``````def find_tangent(x, coefficients):

slope = 0
intercept = coefficients[0]

for i, coefficient in enumerate(coefficients):

if i != 0:

slope += coefficient * i * pow(x, i - 1)
intercept += coefficient * pow(x, i)

return [intercept - slope * x, slope]
``````

I have tested the results against the Symbolab Tangent Calculator and they seem to be okay but please let me know if you find any errors! Also, I would love to see results in other languages so if you have a prefered language that's not mentioned here don't hesitate to post!