Anonymous - 2014-05-02

Well, apparently I'm still in mathematical mode. This is a function which raises a base to an exponent, i.e, Power(base,exponent) and might make a good addition to the Maths.H include file.

I had originally thought Legendre's method would be more efficient, but decided the IF/THEN's added too much overhead given that we're working with small numbers on a microcontroller. And this simpler version has the advantage of using very little program space.

So, here's a demo, from which the function may be extracted if it meets the needs of this community.

;Thomas Henry -- 5/2/2014

;This demonstrates a function to raise a base to a power
;Remember, powers can easily become huge, so it is up to the
;calling program to make certain your numbers remain within
;range. The base and exponent are Byte sized numbers in any
;event. The returned result is a Long. Non-negative numbers are
;assumed throughout.

;Keep in mind that 0 raised to 0 is meaningless and should be
;avoided. But any other non-zero base raised to 0 is handled okay.

;----- Configuration

#chip 16F88, 8                  ;PIC16F88 running at 8 MHz
#config mclr=off                ;reset handled internally
#config osc=int                 ;use internal clock

;----- Constants

#define LCD_IO      4           ;4-bit mode
#define LCD_RS      PortB.2     ;pin 8 is LCD Register Select
#define LCD_Enable  PortB.3     ;pin 9 is LCD Enable
#define LCD_DB4     PortB.4     ;DB4 on pin 10
#define LCD_DB5     PortB.5     ;DB5 on pin 11
#define LCD_DB6     PortB.6     ;DB6 on pin 12
#define LCD_DB7     PortB.7     ;DB7 on pin 13
#define LCD_NO_RW   1           ;ground the RW line on LCD

;----- Variables

dim i, j as byte

;----- Program

dir PortB out                   ;all outputs to the LCD

for i = 1 to 10                 ;do all the way from
  for j = 0 to 9                ;1^0 on up to 10^9
    cls
    print i
    print"^"
    print j
    print "="

    locate 1,0
    print power(i,j)            ;here's the invocation
    wait 1 S
  next j  
next i   

;----- Functions

function power(p_base as byte, p_exp as byte) as long
  ;return p_base raised to the p_exp power
  dim p_copy as byte

  p_copy = p_exp
  power = 1
  do while p_copy
    power = power * p_base
    p_copy--
  loop
end function  
 

Last edit: Anonymous 2014-05-02