ubsuny / 23-Homework6G2

Apache License 2.0
0 stars 9 forks source link

Task 2 - root_simple unable to find root for tanh(x) #26

Open WildJimmy opened 9 months ago

WildJimmy commented 9 months ago

I'm having some issues with task 2. I can't get root_simple to find the roots of tanh(x) when given a positive initial guess. It will always exceed the maximum number of steps. However, for negative guesses it is fine. Any ideas on how to resolve this without changing the algorithm? I'm a little confused because tan and tanh have roughly the same behavior around x = 0 and I do not have this issue with finding the roots of tan

tirthbha commented 9 months ago

@WildJimmy Which method have you adopted to find the roots?

WildJimmy commented 9 months ago

I'm using methods from the rootfinding.py file, specifically here I'm referring to root_simple

def root_simple(f, x, dx, accuracy=1.0e-6, max_steps=1000, root_debug=False):
    """Return root of f(x) given guess x and step dx with specified accuracy.
    Step must be in direction of root: dx must have same sign as (root - x).
    """
    f0 = f(x)
    fx = f0
    step = 0
    iterations = []
    if root_debug:        
        root_print_header("Simple Search with Step Halving", accuracy)
        root_print_step(step, x, dx, f0)
        iterations.append([x,f0])
    while abs(dx) > abs(accuracy) and f0 != 0.0:
        x += dx
        fx = f(x)
        if f0 * fx < 0.0:   # stepped past root
            x -= dx         # step back
            dx /= 2.0       # use smaller step
        step += 1
        if step > max_steps:
            root_max_steps("root_simple", max_steps)
        if root_debug:
            root_print_step(step, x, dx, fx)
            iterations.append([x,fx])
    return x,np.array(iterations)
tirthbha commented 9 months ago

@WildJimmy In my opinion, the tanh function's behavior near x = 0 is indeed similar to tan, but the critical difference is in their asymptotic behavior for large positive and negative x, which impacts the effectiveness of the root_simple method.

WildJimmy commented 9 months ago

I'm not sure. I have to do some better debugging, but since all root simple checks is the function's distance from 0 I don't understand what's appreciably different about tan and tanh, given that the guess is reasonably close to 0... Unless using it for tan has been finding the root NOT at x = 0, but at pi or something... I should check that

tirthbha commented 9 months ago

@WildJimmy I used Bisection and Newton-Raphson methods to get roots, they worked.

tirthbha commented 9 months ago

@WildJimmy Have you sorted out the issue with the root_simple method?

LinxuanHu commented 9 months ago

did you fidured it out?

s4il3sh commented 9 months ago

tanh(x) has only one root that is zero.