Skip to main content
Announcements
Qlik Connect 2024! Seize endless possibilities! LEARN MORE
cancel
Showing results for 
Search instead for 
Did you mean: 
Anonymous
Not applicable

Calculate PRODUCT on negative values

I ended up having a formula which had to apply the PRODUCT function on the daily performances to calculate the aggregated month performance.

The daily performances could be both positive and negative:

DayPerf
01.01.20161%
02.01.2016-1%
03.01.20165%
04.01.2016-20%
05.01.201610%
06.01.20166%

I could not use $(=Concat(Perf,'*')) as I was using a Pivot table where for each level the aggregations should have been on different fields.

Exp(Sum(Log(Perf))) works fine only on positive numbers: Log on negative values produces an error and Sum skips these errors.

I'd like to share the formula for finding the PRODUCT of all the numbers, positive and negative included.

The final formula is the following:

Exp( // PRODUCT function

    Sum(

          Log(

              Fabs(Perf) //Treat all values as if they were positive

          )

    )

)

* ( // Determine final sign

    mod(

          sum(

              sign(

                    sign(Perf) - 1

              )

          ), 2

    ) * -2 + 1

)

The approach is this: execute the PRODUCT function on all the numbers converted to positive numbers and multiply it to 1 or -1 according to what is necessary.

FunctionExplanation
sign(Perf) - 1Remove positive signs: (-1, 0, 1) - 1 => (-2, -1, 0)
sign( sign(Perf) - 1 )Convert all negatives to -1; zeros remain 0
sum(...)Sum up all the negatives to determine if they are odd or even
mod(..., 2)Check if the final number of negative values is odd or even
mod(..., 2) * -2 + 1Convert mod result (1 or 0) into (-1 or 1)

The final expression sounds like: PRODUCT([Positive values]) * [-1 if odd negative values or 1 if even negative values].

Is there any better way to doing this?

3 Replies
swuehl
MVP
MVP

The second part could probably also written as

* If(Mod(Sum(Perf<0),2)=1,-1,1)

Anonymous
Not applicable
Author

Sum should be Count then.

Though I avoid at all cost per record comparisons like sum(perf<0).

swuehl
MVP
MVP

Valeriy Shylin wrote:

Sum should be Count then.

Though I avoid at all cost per record comparisons like sum(perf<0).

No, I think Sum() should be Sum().

And I believe the Sum(perf<0) is not much different from your Sum(Sign(Perf))

[ignoring the additional Sign() and addition for now].

You can also replace the Mod() with Odd / Even:

* If(Odd(Sum(Perf<0)),-1,1)

I think this expression comes closest to your original pseudo code:

[-1 if odd negative values or 1 if even negative values]

Or if you prefer not to use the if() function:

* (Odd(Sum(Perf<0))*2+1)

I am just trying to suggest an alternative approach.

Regards,

Stefan