Based on a recursive implementation of the Chudnovsky algorithm, one of the fastest algorithms to estimate pi. For each iteration, roughly 14 digits are estimated (take a look here for further details).
def f(n):import decimal as d;d.getcontext().prec=n+10;q=lambda n,k=6,m=1,l=13591409,x=1,i=1:(d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+q(n,k+12,(k**3-16*k)*m//i**3,l+545140134,x*-262537412640768000,i+1)if i<n else 13591409);return sum([ord(i)%2 and int(i)for i in str(426880*d.Decimal(10005).sqrt()/q(n//14+1))[:n+1]])
Ungolfed version
def f(n):
import decimal as d
d.getcontext().prec = n + 10
q=lambda n, k=6, m=1, l=13591409, x=1, i=1:\
(d.Decimal(((k ** 3 - 16 * k) * m // i**3) * (l + 545140134)) / (x * -262537412640768000) +
q(n, k+12, (k ** 3 - 16 * k) * m // i**3, l + 545140134, x * -262537412640768000, i+1)if i < n else 13591409)
return sum([ord(i) % 2 and int(i)for i in
str(426880 * d.Decimal(10005).sqrt() / q(n // 14+1))[:n + 1]])
Function q
computes the value of S
(see the reference), than it is used to divide the term 426880 * d.Decimal(10005).sqrt()
and get the value of the approximation of pi.
The precision is controlled by setting the value of d.getcontext().prec
.
A a little bit longer (372 bytes), more golfed but all-in-one version:
f=lambda n,k=6,m=1,l=13591409,x=1,i=0:not i and(exec('global d;import decimal as d;d.getcontext().prec=%d+10'%n)or sum([ord(i)%2 and int(i)for i in str(426880*d.Decimal(10005).sqrt()/f(n//14+1,k,m,l,x,1))[:n+1]]))or i<n and d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+f(n,k+12,(k**3-16*k)*m//i**3,l+545140134,x*-262537412640768000,i+1)or 13591409
Thanks to O.O.Balance to push me to go deeper into this challenge: it was very fun and interesting.
Old answer, based on math.pi
(74 bytes)
import math;f=lambda n:sum([ord(i)%2and int(i)for i in"%.*G"%(n,math.pi)])
Try it online!
N.B.: math.pi
is "The mathematical constant π = 3.141592…, to available precision.", but the digits for the challenge are computed on the fly through the rounding and truncating operations. So, technically this is not a violation of the rules: "all the digits of pi must be calculated by your program at runtime."