Home > database >  How to solve a math sequence in R?
How to solve a math sequence in R?

Time:05-07

EDIT: I could not come up with a more precise question title but please let me know what better title I could use, thanks!

I have a "basic" math problem that I cannot turn into an R code. If I add 4 kg of rock every year to the soil and that 1% of all the added rock dissolves every year, how much rock (in kg) will I have dissolved after n years? (e.g. n=47 years).

Do you know of a code or function in R that could help me calculate this?

Thanks a lot!

To make it clear, the calculation looks like this for the first three years:

YEAR 1

The first year I apply 4 kg and, at the end of the year, I have A1 = 0.01x4 = 0.04 kg of rock dissolved

YEAR 2

The second year, I still have 4-(0.01x4)= 3.96 kg of undissolved rock from the first year and I apply again 4 kg of rock. In total, I have 3.96x4 = 7.96 kg of rock. I will have A2 = 0.01x7.96 = 0.0796 kg of rock dissolved at the end of year 2 AND A1 = 0.04 kg of rock dissolved from year 1

So at the end of year 2, I will have dissolved a total of 0.04 0.0796 = 0.1196 kg of rock

YEAR 3

Total amount of undissolved rock at the beginning of year 3: 4 kg (year 3 application) 3.96 kg (year 2 application) 3.96-(3.96x0.01) = 3.92 kg from year 1 application. In total, I have 4 3.96 3.92= 11.88 kg of undissolved rock. At the end of year 3, I will have A3 = 0.01x11.88 = 0.1188 kg of dissolved rock

Total amount of dissolved rock at the end of year 3: A3 A2 A1 = 0.1188 0.0796 0.04 = 0.2384 kg of dissolved rock

CodePudding user response:

1) If u[i] and d[i] are the undissolved and dissolved rock at the end of year i and if we want to calculate that for n years then:

n <- 3
u <- numeric(n)
u[1] <- 4
for(i in 2:n) u[i] <- (1-0.01) * u[i-1]   4
u
## [1]  4.0000  7.9600 11.8804

d <- cumsum(0.01 * u)
d
## [1] 0.040000 0.119600 0.238404

2) We can alternately use Reduce like this:

n <- 3
u <- Reduce(function(x, y) (1-0.01)*x 4, numeric(n-1), init = 4, acc = TRUE)
u
## [1]  4.0000  7.9600 11.8804

d <- cumsum(0.01 * u)
d
## [1] 0.040000 0.119600 0.238404
  • Related