Jump to content

Recommended Posts

Please any information or suggestion is welcome.

 

Question:

 

1. Does boostC have any inbuilt "rounding" function? One that rounds to the nearest integer e.g. like python's "maths.ceil ( ) function" . I want to manipulate a float number say 3.4 to become 3.5. If I were to do this using the ceil ( ) function:

 

ceil (2 * raw_decimal) / 2

 

where : raw_decimal = 3.4 , the function rounds 6.8 to 7 then dividing by 2 gives 3.5. I basically want to get my numbers to the nearest whole or 0.5 decimal.

 

2. Is there any work around in boostC if there is no inbuilt compiler function to do this?

 

Thanks

Bade

Link to post
Share on other sites

Hi

 

 

You can try this

 

Result = (Int( 2 * Input + 0.5)) / 2

 

The "0.5" offset is commonly used on 4/5 rounding to integer, like the rounding used for school grades.

 

A quick spreadsheet exercise can show you that the step points of this expression are at x.25 and x.75, but you can finetune those limits by adjusting the offset value of "0.5".

 

In "C" it will be somthing like this.

 
#define  REF_OFFSET  0.5
 
float fResult;
float fInput;
long lAux
 
lAux = (long)(2.0 * fInput + REF_OFFSET);   // Typecast to integer truncates the decimal
                                            // part so behaving like the "Int(x)"
                                            // function of a spreadsheet.
fResult = (float)lAux / 2.0; 
 

Note:

This is not a true "Ceil" function, this is a "0.5" rounding.

A true "Ceil" function will result from makimg the "REF_OFFSET" = 0.99999......... or you can implement it in a small function, more or less like this

float Ceil(float x)
{
     if(x >= 0)
       return (x != (float)((long)x)) ? (float)((long)x+1) : (float)((long)x);  // positive number rounds to the integer above
     else
       return ((float)((long)x)); // negative numbers is a simple truncation
}

EDIT Correction: "float((long)x+1)" to "(float)((long)x+1)"

 

Just my 2 cents...

 

 

Best regards

Jorge

Edited by JorgeF
Link to post
Share on other sites

Hi

 

It was a typing error, the float typecast for "x+1" in the first return statement was missing the "()".

Alredy corrected.

 

In fact the code in my previous post was not tested, not even compiled,

I wrote it straight to the forum while replying, so the silly typing bug.

 

 

Best regards

Jorge

Edited by JorgeF
Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...