Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding a Calculator on Python

So I'm trying to program a calculator that operates with 5 digits, and then check its interval. Here is the code:

def CR5(x):
  x=float('%s' % float('%.5g' % x))
  x="{:.4e}".format(x)
  return x

This seems to be working fine, except that the answer is in string form, but that isn't a problem at this stage. However when I try to check the interval, I get this:

code:

def interval(x):
   x=float(CR5(x))
   a=x-1
   b=x+1
   while float(CR5(a))!= x:
       a=float(CR5((a+x)/2))
   while float(CR5(b))!= x:
       b=float(CR5((b+x)/2))
   return a, b

result if x == 4:

(4.0, 4.0)

while I am trying to get (3.9999, 4.0001).

Any idea of what I did wrong? Thank you!

like image 454
L.R. Avatar asked Jun 03 '26 15:06

L.R.


1 Answers

You are running the while loop until a and x becomes equal while you are actually looking for the intermediate value to be equal to x. You should write the loop like this instead:

while float(CR5((a+x)/2.0))!= x:

and

while float(CR5((b+x)/2.0))!= x:

result for x=4:

(3.9999, 4.0001)
like image 77
Selcuk Avatar answered Jun 06 '26 05:06

Selcuk