TransWikia.com

Expression evaluates to a different number when made a function

Mathematica Asked by level1807 on February 4, 2021

The following expression evaluates to zero at large n when just using replacement, but if the same expression is defined as a function f[n], it suddenly evaluates to a nonzero number. Redefining the function by absorbing the denominator into Hypergeometric2F1Regularized again gives a vanishing answer. Applying N to all of these gives a nonzero answer. Is this an issue with precision control, and if so, how do I fix it, and which result should I trust?

exp = n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 2 + n, -1]
f[n_] := n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 2 + n, -1]
f1[n_] := n^2/2 Gamma[n + 1/2] Hypergeometric2F1Regularized[1, 1 - n, 2 + n, -1]
f1[n] == f[n] // FullSimplify
{exp /. {n -> 256.}, f[256.], f1[256.], N[exp /. {n -> 256}], N[f[256]], N[f1[256]]}

Output: {0., 109.439, 0., 109.439, 109.439, 109.439}.

2 Answers

This is fun. Let's make it even more mysterious:

Clear[n]
exp = n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 
   2 + n, -1]
"test with Block:"
Block[{n = 256.}, exp]  (* 0, with a warning *)
Block[{n = 256.}, 
 n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 2 + n, -1]] (* 109.439 *)

Use Trace to see the divergence in evaluation:

Trace@Block[{n = 256.}, exp]
Trace@Block[{n = 256.}, 
  n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 2 + n, -1]]

Bottom line: Use the one that does not give a warning. (And btw, you can evaluate the expression in pieces, which supports this.)

Clear[n]
expr = {n^2/2, Gamma[n + 1/2]/Gamma[n + 2], Hypergeometric2F1[1, 1 - n, 2 + n, -1]};
Times @@ (expr /. {n -> 256.})

Answered by Alan on February 4, 2021

Clear["Global`*"]

exp = n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 2 + n, -1];
f[n_] := n^2/2 Gamma[n + 1/2]/Gamma[n + 2] Hypergeometric2F1[1, 1 - n, 
   2 + n, -1]
f1[n_] := n^2/2 Gamma[n + 1/2] Hypergeometric2F1Regularized[1, 1 - n, 
   2 + n, -1]
f1[n] == f[n] // FullSimplify

(* True *)

{exp /. {n -> 256.}, f[256.], f1[256.], N[exp /. {n -> 256}], N[f[256]], 
  N[f1[256]]} // Quiet

(* {0., 109.439, 0., 109.439, 109.439, 109.439} *)

This is a precision issue with some representations (which alter the sequence of operations). Just avoid machine precision by using arbitrary-precision.

exp /. {{n -> 256.}, {n -> 256.0`15}, {n -> SetPrecision[256., 15]}} // Quiet

(* {0., 109.438999105, 109.438999105} *)

f1 /@ {256., 256.0`15, SetPrecision[256., 15]}

(* {0., 109.438999105, 109.438999105} *)

Answered by Bob Hanlon on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP