What's wrong with my bisection method code?

In summary: I've seen people use whitespace as a brace, which is a horrible idea. I've seen people use parentheses for a brace, which is also a horrible idea. I've seen people use 4 spaces per indent, and I've seen people use 2 spaces per indent. I've seen people use 8 spaces per indent, and I've seen people use 1 space per indent. I've seen people use tabs for indentation, and I've seen people use spaces. I've seen people use tabs for indentation and spaces for alignment. I've seen people use spaces for indentation and tabs for alignment. I've seen people use weird characters for indentation and alignment. I've seen people use 79 characters per
  • #1
Hi Im Paul
2
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
  • #2
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
  • #3
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
  • #4
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
  • #5
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.
 
  • #6
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.
 
  • #7
@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:
[code=python]if pos(funcy(lowy,n), funcy(midy,n)):
highy = midy
else:
lowy = midy
[/code]

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.
 
  • #8
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.
 
  • #9
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!
 

Related to What's wrong with my bisection method code?

1. Why is my bisection method code not converging?

There are several possible reasons for your code not converging. One common issue is using an incorrect function or interval for the root-finding problem. Make sure your function is continuous and has a root within the given interval. Another potential issue could be using an incorrect stopping criterion or an incorrect number of iterations. It is also important to check for any coding errors that may be causing the code to not converge.

2. How do I choose the initial interval for my bisection method code?

The initial interval should be chosen such that it contains at least one root of the function. To do this, you can plot the function and visually identify where the roots are located. Alternatively, you can use the Intermediate Value Theorem to find an interval that contains a root. You may need to adjust the initial interval if the code is not converging.

3. Can I use the bisection method for non-linear functions?

No, the bisection method is only applicable for finding roots of continuous functions. For non-linear functions, you can use other root-finding methods such as Newton's method or the secant method.

4. How do I know when to stop the bisection method?

The bisection method typically stops when the interval becomes sufficiently small, usually when the difference between the upper and lower bounds is less than a specified tolerance. Another stopping criterion could be a maximum number of iterations or when the function value at the midpoint is close to zero.

5. How can I improve the speed of my bisection method code?

One way to improve the speed of the bisection method is to use a more efficient stopping criterion. For example, instead of checking if the difference between the upper and lower bounds is less than a certain tolerance, you can check if the function value at the midpoint is close to zero. Additionally, you can use a more precise data type to represent the interval boundaries to avoid rounding errors. Another approach is to use a more advanced root-finding method that converges faster, such as the secant method or Brent's method.

Similar threads

  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
34
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
4
Views
4K
  • Programming and Computer Science
Replies
7
Views
3K
  • Programming and Computer Science
Replies
6
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
2
Views
908
  • Programming and Computer Science
Replies
11
Views
1K
Back
Top