Search code examples
rplotgraphoperator-keywordtaylor-series

Plotting same equation but different graph. l


I tried to plot Taylor expansion with the exponential function, f(x) = exp( x ) at a = 0 and by n = 1.

At first, I wrote the equation #### n = 1 and plotted it. But It failed to fit the line to graph of Exp(x). And I tried to relocate sign '+' to upper line, as see the equation # n = 1, and it worked.

These Equations are exactly same, except location of the operator sign ( + ).

What is difference between the equations ( #### n = 1, # n = 1 ) for plotting?

Is it important the location of operator signs in plotting?

f1 <- function(x) exp( x )
x <- seq( -1, 1, by = 0.025 )


a <- 0

#### n = 1
f1.10 <- function( x ){
  exp( a ) / factorial( 0 ) * ( x - a )^0 
  + exp( a ) / factorial( 1 ) * ( x - a )^1
}


# n = 1
f1.1 <- function( x ){
  exp( a ) / factorial( 0 ) * ( x - a )^0 +
    exp( a ) / factorial( 1 ) * ( x - a )^1
}



plot( x, exp(x), ylab = "exp(x)", type = "l", lwd = 3 )
curve( f1.1, -0.5, 0.5, add = T, type = "l", lwd = 2, col = "yellow" )
curve( f1.10, -0.5, 0.5, add = T, type = "l", lwd = 2, col = "blue" )

[sample_output]1


Solution

  • In R, + of line head means new line. If you put + at end of line, R recognize the next line in script as continuation of current line.
    So,

    f1.10 <- function( x ){
      exp( a ) / factorial( 0 ) * ( x - a )^0 
      + exp( a ) / factorial( 1 ) * ( x - a )^1
    }
    

    is the same as

    f1.11 <- function( x ){
      exp( a ) / factorial( 1 ) * ( x - a )^1
    }