A root of a "saw-like" function

74 Views Asked by At

Say, we have f(t) = v * t + A * sin(w * t). I call such functions "saw-like": enter image description here

I want to solve saw(t) = C, that is, find a root of saw(t) - C (still "saw-like").

I tried writing down a ternary search for function abs(saw(t) - C) to find its minima. If we are lucky (or crafty), it would be the root. Unfortunately, my code does not always work: sometimes we get stuck in those places:

enter image description here

My code (python3):

def calculate(fun):
    eps = 0.000000001
    eps_l = 0.1
    x = terns(fun, 0, 100000000000000)
    t = terns(fun, 0, x)
    cnt = 0
    while fun(x) > eps:
        t = x
        x = terns(fun, 0, t)
        if abs(t - x) < eps_l:
            cnt += 1
        # A sorry attempt  pass some wrong value as a right one. 
        # Gets us out of an infinite loop at least.
        if cnt == 10:
            break
    return t

def terns(f, l, r):
    eps = 0.00000000001
    while r - l > eps:
        x_1 = l + (r - l) / 3
        x_2 = r - (r - l) / 3

        if f(x_1) < f(x_2):
            r = x_2 
        else:
            l = x_1
    return (l + r) / 2

So, how is it done? Is using ternary search the right way?


My other idea was somehow sending the equation over to the net, passing it to Wolfram Alpha and fetching the answers. Yet, I don't how it's done, as I am not quite fluent at python.

How could this be done?

0

There are 0 best solutions below