-1

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.

Willem Hendriks
  • 1,267
  • 2
  • 9
  • 15
Latexfan
  • 1
  • 2
  • I am not sure what the y is. you have d(x,y) but dont see a y in your distance expression.. is y = f(x) ? – Willem Hendriks Jan 13 '21 at 15:36
  • https://www.sympy.org/en/index.html can both give the derivative and solve to 0, would you consider that as an option? Let me know if you need an example – Willem Hendriks Jan 13 '21 at 16:16
  • I am very new beginner and if you can give give examples to read a function, to deriverte and solve the solution, is perfect. Or you could please use f(x)=1/x see how it works for that example. Thanks for your assistance. – Latexfan Jan 16 '21 at 14:43

1 Answers1

0

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.

Willem Hendriks
  • 1,267
  • 2
  • 9
  • 15