Search code examples
react-nativeanimationsymbolic-mathdeclarativereact-animated

React Native Animated how to implement ReLU (y = 0 for negative x, y = x for positive x)


I'm trying to bind a (native) animation on React Native based on scroll offset animated value of a scroll view. What I basically want to achieve is the ReLU function, that is:

f(x) = 0 if x < 0
f(x) = x if x >= 0

enter image description here

I've tried Animated.multiply to get the square and divide by itself again to get the sign but that doesn't seem to work either.

How can I achieve that function using the declarative Animated API (so no conditionals/ifs or any imperative code) to bind to some animated property?


Solution

  • I've solved the issue using clamping/interpolation. Basically I've set input/output range to be a large negative number to zero, and I've set the extrapolation to clamp:

    const ty = this.props.boundOffset.interpolate({
        inputRange: [-1000,0],
        outputRange: [-1000, 0],
        extrapolate: 'clamp',
    
    })
    

    It worked perfectly.