Simple program problem

A forum for general discussion of the Python programming language.

Simple program problem

Postby RafaelGoncalves » Tue Jul 01, 2014 1:47 pm

Hi, this is my first post, I am starting trying to learn programming and I can't do this simple program right.
It's supposed to find roots of numbers, can someone help me please?

Code: Select all
def withinEpsilon(x, y, epsilon):                   
   """   x, y, epsilon floats. epsilon > 0
      returns True if x is within epsilon of y"""
   return abs(x-y) <= epsilon

def isEven(i):
   """assumes i a positive int
   returns True if i is even, otherwise False"""
   return i%2 == 0

def findRoot(pwr, val, epsilon):
   """assumes pwr an int; val, epsilon floats
   pwr and epsilon > 0
   if it exists,
   returns a value within epsilon of val**pwr
   otherwise returns None"""
   assert type(pwr) == int and type(val) == float and type(epsilon) == float
   assert pwr > 0 and epsilon > 0
   if isEven(pwr) and val < 0:
      return None
   low = -abs(val)
   high = max(abs(val), 1.0)
   ans = (high + low)/2.0
   while not withinEpsilon (ans**pwr, val, epsilon):
      if ans**pwr < val:
         low = ans
      else:
         high = ans
      ans = (high + low)/2.0
   return ans

def testFindRoot(val):   
   """x float, epsilon float, pwr positive int"""
   for pwr in (1, 2, 3, 4, 5):
      ans = findRoot(pwr, val, 0.001)
      if ans == None:
         print 'The answer is imaginary.'
      else: print ans, 'to the power', pwr, 'is close to', x

val = raw_input('Choose a number:')                 
print testFindRoot(val)


It gives me Assertion Error in the line: 'assert type(pwr) == int and type(val) == float and type(epsilon) == float'
Last edited by micseydel on Tue Jul 01, 2014 4:19 pm, edited 1 time in total.
Reason: First post lock.
RafaelGoncalves
 
Posts: 2
Joined: Tue Jul 01, 2014 1:30 pm

Re: Simple program problem

Postby stranac » Tue Jul 01, 2014 11:11 pm

raw_input returns a string, so val is a string and not a float.
If you want to convert it to a float, you can just use the float() built-in.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1092
Joined: Thu Feb 07, 2013 3:42 pm

Re: Simple program problem

Postby RafaelGoncalves » Thu Jul 03, 2014 8:11 pm

stranac wrote:raw_input returns a string, so val is a string and not a float.
If you want to convert it to a float, you can just use the float() built-in.


Thank you very much! Sorry for bothering you with this silly mistake :(
RafaelGoncalves
 
Posts: 2
Joined: Tue Jul 01, 2014 1:30 pm


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 3 guests