PBOR Ch 8 Exercise 1(i)(c)

Discussion in 'CS2' started by rlsrachaellouisesmith, Jul 22, 2020.

  1. rlsrachaellouisesmith

    rlsrachaellouisesmith Ton up Member

    Hi

    When I put together my solution to create the graph and then also tried the exact notation given in the solutions I do not get the same graph as in the solutions. Can you confirm this is definitely correct? I have checked and re-checked my work but cannot see that I have done anything different to the solutions, but still end up with a different graph.

    Many thanks.

    Rachael
     
  2. Andrew Martin

    Andrew Martin ActEd Tutor Staff Member

    Hello

    I believe it's correct. It's hard to check your solution without any code, can you provide your script? At a guess you may be having an issue with where your minus signs are in the function. For example, the below function works:

    logL <- function(x){
    18*x-4*log(30*exp(x)+17)-4*log(27*exp(x)+14)-log(23*exp(x)+14)-
    2*log(22*exp(x)+12)-2*log(20*exp(x)+10)-5*log(18*exp(x)+8)-
    2*log(12*exp(x)+8)-log(10*exp(x)+8)-2*log(7*exp(x)+4)}

    I've highlighted the minus signs at the end of the line - this tells R that the expression is not over and to continue to the next line.

    The below function does not work:

    logL <- function(x){
    18*x-4*log(30*exp(x)+17)-4*log(27*exp(x)+14)-log(23*exp(x)+14)
    -2*log(22*exp(x)+12)-2*log(20*exp(x)+10)-5*log(18*exp(x)+8)
    -2*log(12*exp(x)+8)-log(10*exp(x)+8)-2*log(7*exp(x)+4)}

    Here, R calculates three separate numbers as it does not treat it as one long expression. The way functions work is they return the last number calculated, so this is just returning -2*log(12*exp(x)+8)-log(10*exp(x)+8)-2*log(7*exp(x)+4) and not the full expression.

    A slightly simpler example is as follows:

    my.function = function(x){
    x-
    4
    }

    my.function(3)
    [1] -1

    my.function2 = function(x){
    x
    -4
    }

    my.function2(3)
    [1] -4

    my.function(3) returns 3-4 = -1.
    my.function2(3) returns -4 (effectively ignoring the input) as this is the last calculation line in the function.

    Hope this helps

    Andy
     
  3. rlsrachaellouisesmith

    rlsrachaellouisesmith Ton up Member

    Thank you Andrew, that has helped!
     

Share This Page