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
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
What is the condition that i has to satisfy to be even? (And please don’t post homework questions here.)
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” ?
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
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
thank you!
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.
Thank you very much! Is this ok?
y = sum(0.5^i for i in 1:1000 if iseven(i))
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?
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.)