Change (0, 1] to (0, 1) without branching

I have a random number generator that outputs values ​​from (0, 1] , but I need to provide the output of a function that returns infinity to 0 or 1. How can I send the processed number to (0, 1) without any branches, since it is intended to run on a GPU?

I guess one way is to add a tiny constant and then accept the value mod 1 . In other words, generate from (Ι›, 1 + Ι›] , which turns into [Ι›, 1) . Is there a better way? What should be Ι› ?

+5
source share
1 answer

Update 1

In Haskell, you can find Ι› using floatRange . The C ++ part below applies otherwise.


Note: The answer below was written before the OP expressed the answer to Haskell

You do not specify the implementation language in the question, so I'm going to suggest C ++ here.

Take a look at std::nextafter .

This will allow you to get the next possible value that you can add to the upper limit, which will cause your code to act as if it were included.

As for branching, you can overload the function to avoid branching. However, this leads to code duplication.

I would recommend allowing the branch and letting the compiler do such micro-optimizations if you really don't need performance, and can provide a more specialized implementation than the standard one ( see Pascal Cuoq comments ).

+2
source

Source: https://habr.com/ru/post/1210124/


All Articles