Jump to content
Dave Novo

restricting floating point range

Recommended Posts

Hello,

I know I can do the following to restrict the valid range of integer variables.

 

TNBType= 1..2;

Can I do something similar with floating point. For example, I want to restrict the values of a double precision variable to be between 0.0 to 1.0. I have tried the following

TProbabilityValue=0.0..1.0;
TProbabilityValue:double=0.0..1.0;
TProbabilityValue:double=0..1;

none of the above seem to work. I guess this is not possible, but I figured I would ask.

Share this post


Link to post
3 minutes ago, Dave Novo said:

Can I do something similar with floating point.

No. No language or library support for anything like this. 

Share this post


Link to post

There's always the InRange function

 

https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.Math.InRange

 

function InRange(const AValue, AMin, AMax: Integer): Boolean;
function InRange(const AValue, AMin, AMax: Int64): Boolean;
function InRange(const AValue, AMin, AMax: UInt64): Boolean;
function InRange(const AValue, AMin, AMax: Single): Boolean;
function InRange(const AValue, AMin, AMax: Double): Boolean;
function InRange(const AValue, AMin, AMax: Extended): Boolean;

Share this post


Link to post

Probably you could use a class helper with specific access methods to mimick that behavior. 

Share this post


Link to post

It's pretty verbose, but you can add your own struct with operator overloading (implicit assignment) that can throw an EArgumentOutOfRangeException when you try to stuff values outside of [0.0, 1.0] into it.

 

While you're at it, you can overload the equality operator as well for just the precision

you need.

 

Or perhaps the add operator as well. So that adding 0.75 with 0.40 will result in 1.0. It depends on how you use these values.

 

I'm sure the compiler is clever and won't even allocate more than the needed 4 bytes for the float.

Edited by Der schöne Günther

Share this post


Link to post

Thanks for the suggestions. I was looking for compiler support instead of rolling my own, but all the suggestions above are great.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×