# Translate sum and long variables to Julia (VS Code)

Hi, I want to write code to transform the mathematical expression of:
y=sum from k=0 to k=infinite of x^k/k!
where x and y are long real var.
I try to write the code such this:

function taylor(k)
k = (0:Inf)
x = long(x)
y = long(y)
if n == 0
end
if n>0
for i in 1:n
f = k*i
y= x^k/f
end
@show x
@show y
end
end
(k)=taylor(3)

or:

function taylor(x)
u=0
v=1
k=0
a=1
while ((v-u)/u)>=(1/10^10)
u=u+((x^k)/factorial(big(k)))
k=k+1
v=v+((x^a)/factorial(big(a)))
a=a+1
end
return u
end
(u,v)=taylor(6)
@show u,v

both didn’t work. I am new to Julia and have no experience in coding before. How to represent series of numbers from 1 to infinite to the x function, let say x= int64. And also how to write proper function e.g function taylor(k). What variable should I put inside taylor( ).

Thank you!!!

Calculating the factorial and the power for each iteration is going to be very slow. BigFloats are also slow, but you don’t need them.

For each iteration you add a new term to your sum. Notice that

x_k = x^k/k! \hspace{1cm} x_{k+1} = x^{k+1}/(k+1)!

So x_{k+1} = x_k\,\cdot\, x/(k+1)

function mysum(x, K)
xₖ = one(x) / 1  # zeroth term x^0/0! equals one
s = xₖ  # initialize sum
for k in 1:K
xₖ *= x / k  # update term as shown above
s += xₖ  # update sum
end
return s
end


You should probably check for convergence, that is, occasionally check whether s + xₖ == s, at that point you can stop summing. I’ll leave adding that as an exercise for the reader

5 Likes