Sunday, August 2, 2015

python: math(9)

Abstract: power function

The script:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug  2 08:58:34 2015

@author: yuan
"""

#calculate power

#method 1
a=8
b=1
print a,'powered by', b, 'is', a**b

#method 2
import math
print a,'powered by', b, 'is', pow(a,b)

#method 3
def mypower(x, n):
    half=n/2
    p=1
    while half>0:
       p *= x*x
       half -= 1
       #print p
    if n%2==1:
        p *=x
       
    return p


print a,'powered by', b, 'is', mypower(a,b)

No comments:

Post a Comment