Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to round any proportion into its closest 1/r form

Tags:

r

fractions

When calculating a proportion (0 < x < 1) I am looking to convert that result x into it's nearest 1/r form, so that for example for

x = 0.30 is converted into 1/3

whereas for

x = 0.29 is converted into 1/4

I have been trying different ideas using round() and fractions() from MASS with little success.

What would be your most simple solution in R that could make this work?

like image 880
Sergio Henriques Avatar asked Sep 09 '19 22:09

Sergio Henriques


People also ask

How do you round to the nearest 1?

To round to nearest one, ten, hundred, thousand and so on: if the rounding digit is 0, 1, 2, 3, or 4, change all digits to the right of it to zeroes. if the rounding digit is 5, 6, 7, 8, or 9, add one to the rounding digit and change all digits to the right of it to zeroes.

What is the rounding rule for proportions?

When computing sample sizes needed to estimate a population mean or estimate a population proportion, if there is any non-zero amount to the right of the decimal point, you must round the result UP TO THE NEXT INTEGER.

How do I round to .5 in R?

Note that for rounding off a 5, the IEEE standard is used, ``go to the even digit''. Therefore round(0.5) is 0 and round(-1.5) is -2 . signif rounds the values in its first argument to the specified number of significant digits.


1 Answers

The following might do what you want, returning either the ceiling or the floor of the reciprocal (whichever gives a better result):

f <- function(x) ifelse(abs(1/floor(1/x) - x) < abs(1/ceiling(1/x) - x),floor(1/x),ceiling(1/x))
like image 119
John Coleman Avatar answered Sep 23 '22 15:09

John Coleman