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!
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!
Share Improve this question edited Mar 12 at 13:13 David Moore asked Mar 12 at 12:42 David MooreDavid Moore 1,0306 silver badges16 bronze badges 3 |2 Answers
Reset to default 5Update
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
Naive Solution
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
You can also use numbers::LCM
on the denominators of v
obtained by as.numeric(sub(".*/(\\d+).*", "\\1", MASS::fractions(v)))
library(MASS)
library(numbers)
v <- c(0.1, 0.9, 0.5, (1/3), 0.5344)
Reduce(numbers::LCM, as.numeric(sub(".*/(\\d+).*", "\\1", MASS::fractions(v))))
[1] 3750
cheapr::scm(Vector_1)
returns 3006, which does not work on 0.5344.) This is an interesting effort, but it shows no research and frankly it is not a programming problem so much as a mathematical problem that can be programmed. Good luck finding your efficient solution! (BTW, it's really looking for the LCD of the imperfect fractions, not always straight-forward.) – r2evans Commented Mar 12 at 13:10