Round to nearest 7.5 with limited mathematical functions

69 Views Asked by At

I am working with a piece of software with limited mathematical functions and I need to round a double value to the nearest multiple of 7.5.

Values will be in the range 0 to 360 (of type double).

I believe I can use the formula:

$$Round(x/7.5)*7.5$$

but the software doesn't have a round function (that I can find at least!)

The functions I have available are:

  • Standard add, subtract, multiply and divide.
  • Brackets are permitted
  • ABS(x) - returns absolute value of x
  • COS SIN TAN and their inverse
  • EXP(x) - returns e to power x
  • INT(x) - returns x rounded down to nearest integer (i.e truncates x)
  • LN(x) - returns the natural base logarithm of x
  • LOG(x) - returns the base 10 logarithm of x
  • MOD(x,y) - returns the remainder of x divided by y
  • SQRT(x) - returns the square root of x

They all accept integers or doubles and return appropriate values types.

So is it possible to round to the nearest 7.5 with only these functions?

1

There are 1 best solutions below

2
On BEST ANSWER

Note that $\mathrm{round}(x) = \mathrm{int}(0.5+\mathrm{abs}(x)) \frac{x}{\mathrm{abs}(x)}$ when $x\neq 0$. Since your $x$ is nonnegative, the formula simplifies to $\mathrm{round}(x) = \mathrm{int}(0.5+x)$ and also holds for $x=0$. So, $7.5 \; \mathrm{round}(\frac{x}{7.5}) = 7.5 \; \mathrm{int}(0.5 + \frac{x}{7.5})$