Python What's wrong with my bisection method code?

Click For Summary
The discussion revolves around implementing the bisection method (or binary search method) to solve the equation 10sin(x) - x^3 - N for various values of N. The code provided has two main functions for finding roots, bisectx and bisecty, but the user encounters issues with the y value being incorrect. Key problems identified include an error in calculating the midpoint in bisecty, where the formula should use addition instead of subtraction. Additionally, the logic for determining the new bounds in bisecty is incorrect, as it fails to maintain the requirement that the function values at the bounds must have opposite signs. Suggestions for improving code readability include adding comments and using more descriptive function names. The conversation also touches on the challenges of Python's reliance on indentation, which can lead to errors when modifying code. Overall, the thread emphasizes debugging the bisection method implementation and improving code clarity.
Hi Im Paul
Messages
2
Reaction score
0
Hello, I am assigned to write a code using bisection method (aka binary search method)
The equation is 10sin(x) - x^3 - N where N = 1,2,3,4,5,6,7
My code is
Python:
from math import sin
def neg(a, b):
    return a*b> 0
def bisectx(funcx, lowx, highx,n):
    assert not neg(funcx(lowx,n), funcx(highx,n))
    for i in range(20):
        midx = (lowx + highx)/2.0
        if neg(funcx(lowx,n), funcx(midx,n)):
            lowx = midx
        else:
            highx = midx
    return midx
def h(x,n):
    return 10*sin(x) - x**3 - n
def pos(c, d):
    return c*d<0
def bisecty(funcy, lowy, highy,n):
    assert pos(funcy(lowy,n), funcy(highy,n))
    for i in range(100):
        midy = (lowy - highy)/2.0
        if pos(funcy(lowy,n), funcy(midy,n)):
            lowy = midy
        else:
            highy = midy
    return midy

def l(y,n):
    return 10*sin(y) - y**3 - n

for i in [1,2,3,4,5,6,7]:
    x = bisectx(h, -3, 4, i)
    y = bisecty(l, -3, 4, i)
    print(x, h(x,i))
    print(y, l(y,i))
Mod note: added code tags, which brought back the indentation.
When I enter this, my x value is correct, however my y value is very wrong. I have tried every variation of y, and I get it wrong or an error. please help
 
Last edited by a moderator:
Technology news on Phys.org
That is really hard to read. But I think I found two problems with your code:

First, in your definition of bisecty, you wrote:

midy = (lowy - highy)/2.0​

Shouldn't that be

midy = (lowy + highy)/2.0​

Second, your definition of pos(c,d) checks if c and d are opposite signs. (Why is that called "pos"?) In a binary search to find a zero of f(y), you always want to maintain that f(lowy) and f(highy) have opposite signs.

So you're checking whether f(lowy) and f(midy) have opposite signs. If they do, then you want to make midy the new highy. Otherwise, you want to make midy the new lowy. You are doing just the opposite of that.

Your code says:

if pos(funcy(lowy,n), funcy(midy,n)):
lowy = midy
else:
highy = midy

and it should say:

if pos(funcy(lowy,n), funcy(midy,n)):
highy = midy
else:
lowy = midy
 
  • Like
Likes FactChecker
I am impressed that @stevendaryl could make sense of the code. Python relies heavily on indentation. To preserve indentation in your post, you can bracket your code with [cod=Python]...[/code] (I had to misspell the first "code" to stop LaTex from interpreting it.)
Python:
# The function sameSigns(a,b) returns true if inputs a and b have the same signs.
# If either a or b are 0, or if they have opposite signs, it returns false.
def sameSigns(a, b):
    return a*b> 0
.
Also, some comments would greatly improve the readability of the code and would help you to spot errors. Also, as was pointed out, function names that better indicate what the function does is a great help. Make it easy on yourself by using comments, good function/variable names, etc.
 
Last edited:
  • Like
Likes scottdave
FactChecker said:
I am impressed that @stevendaryl could make sense of the code. Python relies heavily on indentation.

Yes, I consider that a horrible thing about Python. When everything is nicely indented, things are fine. But in my experience, I do a lot of coding by cutting and pasting and modifying, and every time you do that, you run the risk of screwing up the indentation.
 
  • Like
Likes FactChecker
stevendaryl said:
Yes, I consider that a horrible thing about Python. When everything is nicely indented, things are fine. But in my experience, I do a lot of coding by cutting and pasting and modifying, and every time you do that, you run the risk of screwing up the indentation.
I agree. Indentation is a big enough problem when it's just for human understanding. When it can actually cause code problems, it is much more serious.
 
FactChecker said:
Python relies heavily on indentation.

stevendaryl said:
Yes, I consider that a horrible thing about Python.
That's a feature! :oldbiggrin:
The rationale for indentation is that it eliminates the need for C-style braces. Seems to me more of a fix for a non-problem.
 
@Hi I am Paul, if you start new threads that contain code, please use code tags. They are pretty easy to use, and look like this:
Python:
if pos(funcy(lowy,n), funcy(midy,n)):
    highy = midy
else:
    lowy = midy

I fiddled with the code tags above so that you can see what I have written. The same code, without the fiddling renders like the following. The indentation that actually is in the example above (but doesn't appear) now shows up.
Python:
if pos(funcy(lowy,n), funcy(midy,n)):
    highy = midy
else:
    lowy = midy

You can specify the language inside the opening code tag. Above I used code=python, but other options include code=c, code=fortran, and others.
 
Mark44 said:
I fiddled with the code tags above so that you can see what I have written.
I don't want to hijack this thread, but how did you do that? I tried several things recommended on the internet, but they didn't work.
 
FactChecker said:
I don't want to hijack this thread, but how did you do that? I tried several things recommended on the internet, but they didn't work.
I changed the text color of the 'c' in code, and "/c" in the closing tag. Even if the new color is the same as the original color, the COLOR tag prevents the code tag from being rendered.
 
  • #10
Mark44 said:
That's a feature! :oldbiggrin:
The rationale for indentation is that it eliminates the need for C-style braces. Seems to me more of a fix for a non-problem.

I've used Python for years, and it's always annoyed me. Indentation is too fragile.
 
  • #11
FactChecker said:
I don't want to hijack this thread, but how did you do that? I tried several things recommended on the internet, but they didn't work.
Mark44 said:
I changed the text color of the 'c' in code, and "/c" in the closing tag. Even if the new color is the same as the original color, the COLOR tag prevents the code tag from being rendered.

There's a [PLAIN] tag that you can use to disable parsing of BBcode (it won't stop the processing of TeX, though). For example, if you type

[PLAIN][CODE=Python]print("hello")[/CODE][/PLAIN]​

in your post it will simply show as [CODE=Python]print("hello")[/CODE].
 
  • Like
Likes FactChecker
  • #12
wle said:
There's a [PLAIN] tag that you can use to disable parsing of BBcode (it won't stop the processing of TeX, though). For example, if you type

[PLAIN][CODE=Python]print("hello")[/CODE][/PLAIN]​

in your post it will simply show as [CODE=Python]print("hello")[/CODE].
Thanks!
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 34 ·
2
Replies
34
Views
5K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 7 ·
Replies
7
Views
5K
  • · Replies 8 ·
Replies
8
Views
2K