Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding multiples close to a value in r

Tags:

r

I want to find the closest number given that I have three numbers x, y and z . I want to find the closest multiple to z which is closest to x^y.

Some examples:

x <- 349
y <- 1
z <- 4

x <- 395
y <- 1
z <- 7

x <- 4
y <- -2
z <- 2

The result should look like:

  • the closest multiple of 4 to 349 is 348
  • the closest multiple of 7 to 395 is 392
  • the closest multiple of 2 to 1/16 is 0
like image 546
user8959427 Avatar asked Sep 15 '19 22:09

user8959427


2 Answers

We can use

f = function(x, y, z) round(x^y/z)*z

For example

f(349,1,4)
# [1] 348

f(395,1,7)
# [1] 392

f(4,-2,2)
# [1] 0
like image 125
dww Avatar answered Oct 21 '22 14:10

dww


foo = function(x, y, z) {
    tmp = x^y
    r = tmp %% z  #take modulus to find remainder
    tmp - r       #subtract remainder from x^y
}

foo(4, -2, 2)
#[1] 0
like image 37
d.b Avatar answered Oct 21 '22 12:10

d.b