# For the same function, why does /. give a complex result?

I define a very simple function like this,

g[k_] := 1. + 2 Sum[1/(1 + (2 n)^2), {n, 1, k}]

g[50] give the result is: 1.70279.

But g[n] /. n -> 50 give aother result: 1.70279 +0. I, It is a complex, something wrong?

• Apply Chop ... Commented Mar 14, 2015 at 13:45
• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! Commented Mar 14, 2015 at 13:46
• You can format inline code and code blocks by selecting it and clicking the {} button above the edit window. The edit window help button ? is also useful for learning how to format your questions and answers. Commented Mar 14, 2015 at 13:46
• Examine the formula for the general sum g[n]. You will see it is complex, but the values always have a zero imaginary component when n is an integer. Commented Mar 14, 2015 at 13:52
• I am fairly certain that an exact duplicate of this question exists. I could not find it. Here however are a couple of somewhat related ones: (24783), (70031), (76436) Commented Mar 14, 2015 at 13:53

## 2 Answers

Without the 1. +, your expression evaluates to:

1/2 I (PolyGamma[0, 1 - I/2] - PolyGamma[0, 1 + I/2] -
PolyGamma[0, 51 - I/2] + PolyGamma[0, 51 + I/2])


When you add 1., although the imaginary parts cancel, the answer remains a complex number.

The reason you get a real number when you evaluate g[50] is that the sum doesn't use the general form, but finds the specific form (a rational number with a large denominator).

Try comparing these expressions to see what I'm talking about.

2 Sum[1/(1 + (2 n)^2), {n, 1, 50}]
1. + %

2 Sum[1/(1 + (2 n)^2), {n, 1, k}]
% /. {k->50}
1. + %

• g[k_Integer] := 1. + 2 Sum[1/(1 + (2 n)^2), {n, 1, k}] Here _Integer is used for g[k], then g[50] and g[n]/. n->50 have the same result. Commented Mar 14, 2015 at 16:54
Clear[g]

g[k_] = 1 + 2 Sum[1/(1 + (2 n)^2), {n, 1, k}] // FullSimplify


(1/2)(PiCoth[Pi/2] - IHarmonicNumber[-(I/2) + k] + IHarmonicNumber[I/2 + k])

For integer arguments you can use FunctionExpand to get an exact rational result with very large numerator and denominator. Use N to convert to approximate real result.

Table[{n, g[n] // FunctionExpand // N}, {n, 0, 100, 5}]


{{0, 1.}, {5, 1.62227}, {10, 1.66514}, {15, 1.68045}, {20, 1.68831}, {25, 1.69309}, {30, 1.6963}, {35, 1.69861}, {40, 1.70034}, {45, 1.7017}, {50, 1.70279}, {55, 1.70368}, {60, 1.70442}, {65, 1.70506}, {70, 1.7056}, {75, 1.70607}, {80, 1.70648}, {85, 1.70684}, {90, 1.70716}, {95, 1.70745}, {100, 1.70771}}