I have the following vector.
Vector_1 <- c(0.1, 0.9, 0.5, (1 / 3), 0.5344)
I want to multiply each element of this vector by the same number such that each number in the resulting vector is an integer. I want this multiplier to be the lowest it possibly can be.
What is the best way to accomplish this task?
For example, the vector c(0.5, (1 / 3), (2 / 7))
could be multiplied by 42
(2 * 3 * 7
) to make the vector c(21, 14, 12)
.
Thanks!
As pointed out by @Mark Dickinson's comment, it is found that the naive solution cannot secure the correct solution due to precision loss. To play things safe, the idea from @Tim G's solution based on MASS::fractions
should be applied.
v <- c(0.5, (1 / 49), (2 / 7))
library(MASS)
d <- Reduce(
\(x, y) (x * y) / (\(x, y) ifelse(!y, x, Recall(y, x %% y)))(x, y),
read.table(text = attr(fractions(v), "fracs"), sep = "/")$V2
)
and we will obtain
> d
[1] 98
Given v <- c(0.1, 0.9, 0.5, (1 / 3), 0.5344)
, a naive (not optimized for efficiency) solution is using repeat
d <- 1
repeat {
if (all((v * d) %% 1 == 0)) {
break
}
d <- d + 1
}
where you will obtain
> d
[1] 3750