For loop to evaluate summation


#1

I have to evaluate:

How can I evaluate it from this point on?

for i=1:1000
    if y=0.5^i ==
        display("even")
    else
        display("odd")
    end
end

#2

What is the condition that i has to satisfy to be even? (And please don’t post homework questions here.)


#3


#4

It’s just an exercise to learn how to write in julia, and i’m asking for help since i just started yesterday.
If i goes from 1 to 1000 and I have to take only even values of y then what should I put after the equal sign, in other words how can i express in code “take only even values” ?


#5

:smirk:


#6

http://docs.julialang.org/en/release-0.5/manual/mathematical-operations/


#7

What’s the point of these answers? If my piece of code is wrong you could just write it’s wrong. I know where the documentation is


#8

In Julia (or programming in general), there are always several different ways to solve a problem.

One way to check if a number is even in Julia is to use the function “iseven”, eg

if iseven(3)
println(“3 is even”)
end

Another is to realise that a number is even if the remainder when you divide by 2 is 0:

a = 3
if a % 2 == 0

end


#9

thank you!


#10

i think you started from the wrong angle. you have for, which is a “do this” sorta thing, while you need an expression, a “value” kinda thing.

the top level is a sum. in julia, it is sum.

inside the sum, you have an expression to be evaluated at points. in julia, it is a generator, that is, a for inside parens with a range and an if to select only evens. iseven checks for even-ness. example generator: (2i for i in 5:100 if isprime(i))

the whole thing must fit in one line.


#11

Thank you very much! Is this ok?

y = sum(0.5^i for i in 1:1000 if iseven(i))

#12

Learning how to develop a test to check your code is the most important thing in programming. So let me throw it back at you: what are some ways that you can check that it’s okay?


#13

One way to make code like this more useful (and to answer @ChrisRackauckas’s question) is to not “hard-code” numerical values like 1000, but rather to make them variables. In this case, it would be natural to want to sum over 1:something for different values of something, so we turn it into a function:

my_sum(N) = sum(0.5^i for i in 1:N if iseven(i))

and then call

my_sum(2)
my_sum(3)

etc.
(Note that my_sum(1) gives an error, since there is nothing to sum over.)