HDembinski / HDembinski.github.io

Write-ups
MIT License
22 stars 5 forks source link

Wrong calculation of errors by value_and_covariance #7

Closed acampove closed 2 years ago

acampove commented 3 years ago

Hi,

In your example you show:

image

which for the error is equivalent to using:

image

but you get 0.3. Maybe I am tired, but I think the output is not right.

Cheers.

mikedram0 commented 3 years ago

Same, the error of the variable is outside of the square in the calculation of expr2. Simply move c inside the square.

acampove commented 3 years ago

Same, the error of the variable is outside of the square in the calculation of expr2. Simply move c inside the square.

I do not understand, what do you mean? Are you talking about?

image

acampove commented 3 years ago

Hi,

Ok, I fixed it following @mikedram0, the fix looks like:

#-------------------------------------------------------
def value_and_covariance_gen(expr, variables):
    expr = sympy_parse_expr(expr)

    symbols = sympy.symbols(variables)
    cov_symbols = sympy.symbols(tuple("C_" + k for k in variables))
    expr2 = sum( (expr.diff(s) * c) ** 2 for s, c in zip(symbols, cov_symbols))
    expr2 = expr2.simplify()

    fval = sympy.lambdify(symbols, expr)
    fcov = sympy.lambdify(symbols + cov_symbols, expr2)

    def fn(**kwargs):
        x = tuple(v[0] for v in kwargs.values())
        c = tuple(v[1] for v in kwargs.values())
        return fval(*x), fcov(*x, *c)

    return fn
#-------------------------------------------------------
def value_and_covariance(expr, **kwargs):
    val, err2 = value_and_covariance_gen(expr, tuple(kwargs))(**kwargs)

    err = math.sqrt(err2)

    return (val, err) 

Cheers.

HDembinski commented 2 years ago

Hi,

In your example you show:

image

which for the error is equivalent to using:

image

but you get 0.3. Maybe I am tired, but I think the output is not right.

Cheers.

This is a misunderstanding, the second number is not the error for the value, but the variance for the value, which is standard deviation squared. The implementation is correct. The function also returns the standard deviation squared.

acampove commented 2 years ago

Hi, In your example you show: image which for the error is equivalent to using: image but you get 0.3. Maybe I am tired, but I think the output is not right. Cheers.

This is a misunderstanding, the second number is not the error for the value, but the variance for the value, which is standard deviation squared. The implementation is correct. The function also returns the standard deviation squared.

But if the errors are 0.1 and 0.2, shouldn't the variance be 0.05? Or you mean the variance of a sample with values 1 and 2, ignoring the errors? That would be 0.5, not 0.3.