Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

python - A root of a "saw-like" function

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?

question from:https://stackoverflow.com/questions/65644783/a-root-of-a-saw-like-function

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...