What does it mean in Go that the pre and post statements of a for loop are empty, like in the following example?
sum := 1
for ; sum < 10; {
sum += sum
}
fmt.Println(sum)
Remember that a for loop is the same as a while loop.
Your code can be rewritten in other languages as
sum := 1
while(sum < 10) {
sum += sum
}
fmt.Println(sum)
In a for loop, there are 3 parts.
for(initial statement ; condition ; end statement usually iterate)
This is equivalent to
initial statement
while(condition) {
Stuff here
End iteration statement
}
The reason your loop can be written withiut the pre and post statements is because you've specified them in other parts of the code.
It behaves like a while in other languages. You don't need the two semicolons:
sum := 1
for sum < 10 {
sum += sum
}
fmt.Println(sum)
A for loop has three elements: initialization statement, condition check, and variable change.
for <initialization statement>; <condition check>; <variable change>{
<actual body>
}
The initialization statement is executed only once when the loop starts. Based on the name, it initializes something (in a lot of cases a variable you iterate through). If it is omitted, then it does nothing
The condition check verifies whether the condition evaluates to true. If it is not, the loop stops. If it is omitted, then it is always true.
The variable change is modifying variables during each iteration of the loop. Most of the time, the iterated variable is increased/decreased, but you can do whatever you want. If it is omitted, it does nothing
After this explanation, you can see that this loop does nothing during your initialization and post condition phase.
You also do not need to use semicolons here. This will be enough.
sum := 1
for sum < 10 {
sum += sum
}
You can even write a loop like this: for {} which will never stop executing, or do something like a while loop:
t := 10
for t > 0{
t--
}
Note that inside your initialization, condition, and change phase you can use many expressions (not just one). So with a simple while loop you can do something like:
for f1, f2, n := 1, 1, 10; n > 0; f1, f2, n = f2, f1 + f2, n - 1{
fmt.Println(f1)
}
which creates Fibonacci numbers—see Go Playground. Showing this not because this is the best way to write it, but rather because it is possible.
Related
I want to get a cummulative relative Performance Line.
I get this error message. I don't know what i am doing wrong. Im trying it now for some time now. Can you help me?
Error: "Mismatched input '|PE|' expecting 'end of line without line continuation'."
change = (close[1]-close[2])/close[2])
n = 252
sum = 0
sais(change, n) => for i=0 to n-1
sum := sum + change [n]
plot(sais, color=color.blue)
The weird error is most likely caused by the fact that you use both the single-line and the multi-line function declaration syntax. It has to be multiline because of the for cycle, so the first line after => should be empty, and the code should start on the next line, indented. This is how your function should look (formatting-wise):
sais(change, n) =>
for i=0 to n-1
sum := sum + change [n]
Note that this won't work either because the function cannot modify a global variable sum. You'd need to create a local variable inside the scope of the function to store the value and then return it and assign it to your global sum. Depending on what you want to achieve, it might look something like this:
<...>
sum = 0
sais(change, n) =>
local_sum = 0
for i=0 to n-1
local_sum := local_sum + change[n]
local_sum
sum := sais(change, n)
Does anyone know if the following can be an example of firstprivate in openmp?
rowstr[0] = 0;
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
nza = rowstr[nrows] - 1;
firstprivate variable is rowstr and j is a private variable.
Actually not, if you use the firstprivate clause you may have inconsistency in your output as some values would never be updated, clarifying:
Let's suppose it's an array of size 4 and you have 2 threads, one thread you get iterations 0 and 1 and the other 2 and 3 (in a perfect world). If you use the firstprivate clause the second thread will sum the position 2 of the array with was initially in the array in position 1, instead of summing it with the previous iteration as the sequential version would do.
Not just that, this particular loop have dependency issues and you should use something like a sum reduction in nza.
I'm trying to decrement the counter of a for loop as the loop is running. Unfortunately, Lua doesn't seem to allow that. This piece of code should run forever:
for i = 1, 100 do
print (i)
i = i - 1
end
but it does, in fact, simply print the series 1-100. Is that by design? If so, how do I decrement the counter of a running loop (for example because the current cycle was disqualified and should run again)?
It's by design. From Lua reference manual:
3.3.5 – For Statement
All three control expressions are evaluated only once, before the loop starts. They must all result in numbers.
So modifying the value of i inside the loop won't change how the loop runs.
for i = 10, 1, -1 do
print(i)
end
If you want to step backwards through a table then do:
for i = #SomeTable, 1, -1 do
print(SomeTable[i].someproperty)
end
Yu Hao above linked to the correct manual page, but quoted the wrong part of it.
Here is the correct quote
for v = e1, e2, e3 do block end
is equivalent to the code:
do
local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
if not (var and limit and step) then error() end
while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do
local v = var
block
var = var + step
end
end
[..]
var, limit, and step are invisible variables. The names shown here are for explanatory purposes only.
In other words, the variable that's being looped over (called "var" above) and the variable exposed to the developer (called "v" above) are different. There is no way to access the former.
I have a forvalues loop:
forvalues x = 1(1)50 {
/* Code goes here */
}
Instead of 50, ideally, I would like that value to come as follows. I have a variable name. Let length = length(name). Whatever the largest value is for length, I would like that to be in place of the 50. I could not figure how to write a forvalues loop in which the end point was not directly stated numerically.
I am thinking that I could deduce the maximum length of the variable as follows:
gen id = 1
gen length = length(name)
by id, sort: egen maxlength = max(length)
From there though I do not know how to store this value into the for loop.
Alternatively, would this be better coded by a while loop?
Something like:
gen x = 1
while (x <= maxlength) {
/* Same Code Here */
replace x = x + 1
}
Based on the documentation I've read, it is possible to use macros but with the caveat that changing the end of the range within the forvalues loop has no effect on the number of times the loop will occur. For instance, if length(name) is 50 when the forvalues loop starts, and you change the length of name within the loop, it will still only loop 50 times.
Technically, you'd be better off using a while loop since forvalues was intended to be used when the end of the range is a literal value. You can use a forvalues loop, but you should use a while loop.
Here's my source to back this up:
http://www.stata.com/manuals13/pforvalues.pdf
Specifically:
Technical note
It is not legal syntax to type
. scalar x = 3
. forvalues i = 1(1)x' {
2. local x =x' + 1
3. display `i'
4. }
forvalues requires literal numbers. Using macros, as shown in the following technical note, is
allowed.
And:
Using macros, as shown in the following technical note, is
allowed.
Technical note
The values of the loop bounds are determined once and for all the first time the loop is executed.
Changing the loop bounds will have no effect. For instance,
will not create an infinite loop. With `n' originally equal to 3, the loop will be performed three
times.
local n 3
forvalues i = 1(1)`n' {
local n = `n' + 1
display `i'
}
Output:
1
2
3
Here is the trick with Stata which I think may work for you. I am using the data auto from Stata datasets.
sysuse auto
Suppose the variable name here be price. Now you want the length of variable price.
sum price
gen length=r(N)
To see what is r(N) type return list after running the sum price.
In your loop it goes like follows: (Updated as per #Nick)
forvalues x = 1/`r(N)'{
/* Code goes here */
}
OR:
local length=r(N)
forvalue i=1/`length'{
dis "`i'"
}
Note: It is not clear why you want for loop.So my answer is restricted to what you only asked for.
#Metrics' first code won't quite work. Here is a better way, cutting out what I call the middle macro.
Start with something more like
. su price, meanonly
. forval j = 1/`r(N)' {
An equivalent approach to the one proposed by #Nick and #Metrics is the following:
sysuse auto, clear
count if !missing(price)
forvalues x = 1 / `r(N)' {
/* Code goes here */
}
I am solving 1d heat equation with neumman boundary conditions by finite difference method on maple but my code is not working please can anyone of you suggest me some better code for this equation on maple..
restart;
with(LinearAlgebra);
FX := 1;
FT := 0.5e-1;
M := 5;
N := 5;
M1 := M-1;
H := FX/M;
K := FT/N; c := 1;
r := c^2*K/H^2;
loop for initial condition;
for i to M1 do V[i, 0] := cos(Pi*i*H) end do;
loop for boundary condition;
for j to N do V[-1, j] := V[1, j] end do;
for j to N do V[M+1, j] := V[M-1, j] end do;
loop for discretized equation;
for j from 0 to N-1 do for i to M-1 do V[i, j+1] := (1-2*r)*V[i, j]+r*V[i-1, j]+r*V[i+1, j] end do end do;
please friends let me know why my last loop is not executing.
Very much a subtlety of Maple. The loop is executing - it just isn't printing the results. Every level of statement nesting adds one to the "printlevel" of the statement. Entering a procedure adds 5 to the printlevel of the containing procedure. The interactive session is level 0. The results of statements are only printed if their printlevel is less than or equal to the global variable printlevel which defaults to one. To see your loop execute, try
printlevel := 4;
Which prints up to 4 levels of nesting but not into any procedure calls. See ?printlevel for the full details.
On a side note, you may want to evalf the cos calls to ensure you get floating point values.