Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Python (3.8) I try make a script that takes a function f(x) as input, e.g;

f(x) = 1/x

If we define the define y = f(x), as a line on the euclidean space, we can calculate the distance d() from the origin (0,0) for each point (x,f(x)) on the line as;

d(x,y) = sqrt(x^2+(f(x))^2)

My goal is to find the x such that the above distance is minimised. This can be done by solving

2x+2f(x)*f'(x) = 0

I will be grateful for help. Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
485 views
Welcome To Ask or Share your Answers For Others

1 Answer

Example in sympy (not expert on sympy);

from sympy import *
from sympy.solvers import solve

x, y, z = symbols('x y z')

g = 1/x

h = 2*x + (2*g) * (diff(g,x))

solve(h,x)

This will return [-1, 1, -I, I] so -1 and 1 should be real answers;

distance = x**2 + g**2

distance.subs(x,1)
distance.subs(x,-1)

I did not sqrt() in distance, but I hope you get an idea how this could be solved in sympy . This is 1 way, there are package to approximate the derivative, and find roots, which should also work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...