Want to find x^y and maintain sign, ie squaring negative numbers

Hi all,

I have a program that measures angles - positive and negative. I’d like to raise them to a power but maintain their sign when I use them later. To be clear, I need .5 degrees to be squared to .25… 2 becomes 4… but I also want -.5 to become -.25… -2 returns -4… etc. We all know that a negative times a negative is a positive and naturally the built in “pow” function always returns positive when given a negative base value. I have been trying all night to write a simple function to handle this for me: By taking 2 floating inputs (a base and an exponent), checking if the base is < 0 and setting a int variable called “sign” to -1. Later in the function (after the power has been found) the result of pow gets multiplied by sign to return it to the correct polarity. I’ve tried a dozen different permutations of the code below but the result is always the same… positive result return correctly, anything that results in a negative result returns 0.00. This includes manually multiplying “result” by -1 or removing the “if” code and initializing sign to -1. I need a second opinion:

void setup() {
Serial.begin(115200); //Initialize Serial Port
}

void loop() {

  double newval = scale(2.0,2.0);
  
  Serial.println(newval);

  delay(200);  
}

double scale(float input, float factor)
  {  
  int sign = 1.0;

  if (input < 0.0){
  sign = -1.0;
  }

  double result = pow(input, factor);
 
  result = result * sign;

  return result;

}
  double newval = scale(-2.0,2.0);

Prints -4.00 for me.

Pete

  Serial.println(newval);

So, you know how to print stuff. Like input, sign, and result. But, you don’t. Why not?

at least this line is ambiguous

int sign = 1.0;

Try this variation

void setup() 
{
  Serial.begin(115200);

  for (int i = -50; i <= 50; i++)
  {
    double newval = scale(i * 0.12345, 2.0);
    Serial.println(newval, 4);
  }
  Serial.println("\ndone...");
}

void loop() 
{
}

double scale(float input, float factor)
{
  double value = pow(input, factor);
  if (input < 0.0) value = -value;  // only adjust calculated factor when input is negative. 
  return value;
}