Search code examples
rvectorpi

R- Every Other Number of a Sequence Negative


I'm trying to generate a series of vectors to calculate the approx. value of Pi using this formula given: Pi = 4 (1- (1/3) + (1/5) -(1/7)... for 7 terms. I made a sequence for the denominator values as such

number.terms3c <-7
seq.vec3c <- seq(from = 1, by = 2 , length.out = number.terms3c)

and would then use that vector to get the reciprocals with

recip.vec3c <- (1/ seq.vec3c)

But in order to sum them, I was thinking I needed to get every other value to be negative (hence the alternating + and - values.

Is there a simple code I can learn to do this?


Solution

  • You can use rep to create what you want to multiply by.

    > recip.vec3c * rep(c(1,-1), length.out = number.terms3c)
    [1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
    [7]  0.07692308
    

    with that said... I only used that to avoid the warning. If you don't particularly care about that you can be fast and loose with the vector recycling that R does and just multiply by c(1, -1).

    > recip.vec3c * c(1, -1)
    [1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
    [7]  0.07692308
    Warning message:
    In recip.vec3c * c(1, -1) :
      longer object length is not a multiple of shorter object length