问题:
我正在寻找一个可以用来计算任何多项式函数在 x 处的正切的万能函数。我对使用的语言无动于衷,尽管首选 JavaScript 或 Python!我应该能够以 a + bx + cx^2 + dx^3 ... 等格式传入任何 x 值和系数数组。
示例函数格式:
function findTangent(x, coefficients) {
// Do differential calculus here.
return [tangentIntercept, tangentSlope]
}
示例功能测试:
假设我有函数,y = 2 + 7x + 5x^2 + x^3,我想在 x = -2 处找到切线.我可以像这样调用此函数,findTangent(-2, [2, 7, 5, 1])
并获得像这样的返回值,[-2, -1]
表示切线,y = -2 - x。
注意事项:
我在 Math Stackexchange 上寻找答案和谷歌搜索,但所有结果都是数学语法而不是代码。我想要一个编程解决方案,与有趣的符号和数学术语相比,我更喜欢循环和 if 语句!
最佳答案
好吧,经过一天的努力,我想我已经找到了 JavaScript 和 Python 的解决方案!
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]
}
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]
我已经针对 Symbolab Tangent Calculator 测试了结果它们似乎没问题,但是如果您发现任何错误,请告诉我!此外,我很乐意看到其他语言的结果,所以如果您有此处未提及的首选语言,请不要犹豫发布!
关于javascript - 求任意多项式函数在 x 处的正切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65963425/