0

I am using below Matlab code to calculate power function [ without using built-in function] to calculate power = b^e. At the moment , I am unable to get power function going that support fractional exponential values b^(1/2) = sqrt(b) or 3.4 ^ (1/4) to calculate power due inefficient approach , because it loops e times. I need help in efficient logic for fractional exponent. Thank you

b = [-32:32]; % example input values
e = [-3:3];   % example input values but doesn't support fraction's
    power_function(b,e)
        p = 1;
        if e < 0
            e = abs(e);
            multiplier = 1/b;
        else
            multiplier = b;
        end
        
        for k = 1:e
            p(:) = p * multiplier; %  n-th root for any given number 
        end
PedroRodriguez
  • 368
  • 2
  • 9
Coder
  • 27
  • 7
  • What is the reason for wanting to write your own power function? You obviously can't code up fractional powers using a for-loop as you have written. So what is the actual requirement? The code you have written has errors anyway. E.g., you should be using 1./b instead of 1/b. And the for-loop indexing you have written won't work as you expect if e is a vector. – James Tursa Feb 28 '22 at 22:47
  • With own power function allows to implement fixed point on a DSP. Yes, I know e is a vector and 1/b to 1./b suggestion doesn't make difference (If you have example, pls share impact). The way forward is - from integer exponent to fraction exponent. There method like Newton Raphson, Taylor series or maclaurin . Any psuedo example in the context is welcome – Coder Mar 01 '22 at 02:40
  • see [Power by squaring for negative exponents](https://stackoverflow.com/a/30962495/2521214) and all the sublinks in there ... so you just do power by squaring for integer part and do power by rooting with the fractional part ... or use `log2,exp2` approach... btw. why test DSP stuff with matlab??? I think you would be much better off with `C` or if you got old IDE then C++ (new IDEs usually do not support C++ correctly on DSP and MCU , one of the reason I still use old stuff like AVR32 studio 2.7, you can forget C++ on STM and TI ...) – Spektre Mar 01 '22 at 08:05
  • @Spekte, Do you have any sample / pseudo code algorithm that you can share ? Thanks – Coder Mar 04 '22 at 17:12

0 Answers0