Turn a float into a value between 0 and 1 (inclusive)?

Petar Petar
Tue Nov 21 10:01:16 UTC 2017


On Tuesday, 21 November 2017 at 09:53:33 UTC, Petar Kirov 
[ZombineDev] wrote:
> On Tuesday, 21 November 2017 at 09:21:29 UTC, Chirs Forest 
> wrote:
>> I'm interpolating some values and I need to make an 
>> (elapsed_time/duration) value a float between 0 and 1 
>> (inclusive of 0 and 1). The elapsed_time might be more than 
>> the duration, and in some cases might be 0 or less. What's the 
>> most efficient way to cap out of bounds values to 0 and 1? I 
>> can do a check and cap them manually, but if I'm doing a lot 
>> of these operations I'd like to pick the least resource 
>> intensive way.
>>
>> Also, if I wanted out of bounds values to wrap (2.5 becomes 
>> 0.5) how would I get that value and also have 1.0 not give me 
>> 0.0?
>
> Is this what you're looking for:
> https://www.desmos.com/calculator/8iytgsr3y3
>
> In which case that would be simply:
> T zeroToOne(T)(T val) { return val % 1; }

The problem, as you can see in the plot is that 0.9(9) remains 
0.9(9), however 1.0 and 1.0000001 become 0.0 and 0.0000001 
respectively and there's no way around this due to the inherent 
discontinuity of the function.


More information about the Digitalmars-d-learn mailing list