What am I doing wrong?

Joined
Aug 19, 2024
Messages
2
Reaction score
0
I'm trying to shorten
Code:
if f_1 == 0:
        roots.append(critical_points[-1])
    elif f_1 > 0:
        x_0 = critical_points[-1]

        x_1 = x_0 + 1
        f_1 = f(polynomial, x_1)

        if f_1 < f_0:
            while f_1 > 0:
                x_1 += 1
                f_1 = f(polynomial, x_1)
            if f_1 == 0:
                roots.append(x_1)
            else:
                roots.append(bisection(polynomial, x_0, x_1, d))
    else:
        x_0 = critical_points[-1]

        x_1 = x_0 + 1
        f_1 = f(polynomial, x_1)

        if f_1 > f_0:
            while f_1 < 0:
                x_1 += 1
                f_1 = f(polynomial, x_1)
            if f_1 == 0:
                roots.append(x_1)
            else:
                roots.append(bisection(polynomial, x_0, x_1, d))

to

Code:
if f_1 == 0:
        roots.append(critical_points[-1])
    else:
        direction = 1 if f_1 > 0 else -1

        x_0 = critical_points[-1]

        x_1 = x_0 + 1
        f_1 = f(polynomial, x_1)

        if f_1 * direction < f_0:
            while f_1 * direction > 0:
                x_1 += 1
                f_1 = f(polynomial, x_1)
            if f_1 == 0:
                roots.append(x_1)
            else:
                roots.append(bisection(polynomial, x_0, x_1, d))

but the output does not stay the same. What am I doing wrong? Is it something with the direction variable?
 
Joined
Sep 21, 2022
Messages
159
Reaction score
23
If you want to flip > to < you need to multiply both sides by -1.

if f_1 > f_0 is true, then -f_1 < -f_0 is true
Code:
if f_1 * direction < f_0 * direction:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,928
Messages
2,570,068
Members
46,513
Latest member
JacklynMcC

Latest Threads

Top