3 ms·
Say we changed the problem to the geometric mean of non-negative numbers (instead of positive). This allows us to early-out if zero is encountered. It's obviou
by ridiculous_fish 9y ago
Say we changed the problem to the geometric mean of non-negative numbers (instead of positive). This allows us to early-out if zero is encountered.
It's obvious how to change the imperative code: `if (x[i] == 0) return 0;` What would this optimization look like in APL or J?
- efnx 9y agoI haven’t used APL but it looks like it has list comprehensions, so a simple “x != 0,” would work there
- avmich 9y agoGeometric mean is nth root of product of n numbers. If you replace any of those numbers with 0, it will all collapse to 0 - perhaps not what you want. But it's not hard to write such a program: geometric_mean1 =: (+/ % #) &. (^."1) @: (0&>.) geometric_mean1 2 4 8 4 geometric_mean1 _2 4 8 0 If you want to replace negative numbers with their positive counterparts, you may first replace a number with its absolute value: geometric_mean2 =: (+/ % #) &. (^."1) @: (>. -) geometric_mean2 _2 4 8 4 geometric_mean2 2 4 8 4 Original geometric_mean probably meant to be geometric_mean =: (+/ % #) &. (^."1) - note the copula (assignment symbol) and rank of first verb (^.) .
- draw_down 9y agogeometric_mean1 =: (+/ % #) &. (^."1) @: (0&>.) Just this makes me want to cry. Good lord. Even if you like functional programming why would you want it to look like this?!