What's wrong with my bisection method code?

Click For Summary

Discussion Overview

The discussion revolves around a user's implementation of the bisection method in Python to solve the equation 10sin(x) - x^3 - N for various values of N. Participants are examining the user's code for errors and providing suggestions for improvement, focusing on both technical aspects of the code and readability.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Meta-discussion

Main Points Raised

  • One participant identifies a potential error in the calculation of the midpoint in the bisecty function, suggesting it should be (lowy + highy)/2.0 instead of (lowy - highy)/2.0.
  • Another participant points out that the logic in the pos function may be misapplied, arguing that it should check for opposite signs between f(lowy) and f(highy) rather than the current implementation.
  • Several participants comment on the readability of the code, suggesting that better function names and comments would help clarify the code's purpose.
  • There is a discussion about the challenges of maintaining proper indentation in Python, with some participants expressing frustration over how it can lead to errors.
  • One participant shares a method for preserving code indentation in forum posts using specific formatting tags.

Areas of Agreement / Disagreement

Participants generally agree on the need for code readability improvements and the importance of correct implementation of the bisection method. However, there are differing opinions on the merits and drawbacks of Python's indentation requirements, with no consensus reached on this topic.

Contextual Notes

Some participants note that the code's readability could be enhanced with comments and clearer function names, which may help in identifying errors. Additionally, the discussion highlights the potential for misunderstandings related to the logic of the bisection method as implemented in the user's code.

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   Reactions: 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   Reactions: 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   Reactions: 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   Reactions: 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
6K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 7 ·
Replies
7
Views
5K
  • · Replies 8 ·
Replies
8
Views
2K