0

I was able to make this program (python 3.9) for my assignment work, but I am having trouble understanding the logic behind it.

I needed to find the root of the polynomial function f(x) = ^3 − 4^2 + 3 − 4. The variables were provided, so I only was required to write the function, a while loop to find the root, and format the output. Part of the required framework was to "execute until the absolute value of val1 and val2 are both less than 0.000001"

My first attempt was

x1 = 0
x2 = 5
val1 = x1**3 - (4*x1**2) + 3*x1 - 4
val2 = x2**3 - (4*x2**2) + 3*x2 - 4
n = 0

while abs(val1) or abs(val2) >= .000001: 
    n += 1
    new_x = (x1+x2)/2
    new_val = (new_x**3) - (4 * new_x**2) + (3 * new_x) - 4
    if new_val < 0:
        x1 = new_x
        val1 = new_val
    else:
        x2 = new_x
        val2 = new_val
        
solution = (x1+x2)/2

print(f"{'The approximate solution is x = '}{solution:.7f}{'.'}")
print(f"{'The algorithm took '}{n}{' iterations to converge.'}")

My reasoning for choosing OR was: both abs(val1) and abs(val2) must be <.000001, so as long as one of the values is greater than or equal to .000001, then the loop will continue to execute. However this caused the loop to run indefinitely. I was able to fix this and complete the assignment by changing the line to:

while abs(val1) and abs(val2) >= .000001:

My confusion stems from my belief that this exits the loop when only one of these statements becomes false, as opposed to both.

Thank you in advance for any guidance you may be able to provide.

MArBel
  • 3
  • 3
  • The duplicate has nice ideas, especially the any-map variant, but here `A>eps or B>eps` could also be combined to `max([A,B])>eps`. – Lutz Lehmann Jul 25 '21 at 13:00

2 Answers2

1

it will run if you change your code to following:

while abs(val1) >= .000001 or abs(val2) >= .000001: 
Fatih Atalay
  • 134
  • 1
  • 1
  • 8
1

In python, like many programming languages, a number (e.g. an integer, float) used as the predicate will resolve to true unless that number is 0. For example,

if 2:
   print('2')
if 0.1:
   print('0.1')
if 0:
   print('0')

In the above code, only 2 and 0.1 will be printed. In your scenario while abs(val1) or abs(val2) >= .000001: the first predicate (abs(val1)) was always resolving to true so the while loop was never exiting

ziv
  • 99
  • 7