What does for i = 1 ; i <= power ; 1 += 1) { mean? - tags

Sorry for pretty basic question.
Just starting out. Using flowgorithm to write code that gives out a calculation of exponential numbers.
The code to do it is:
function exponential(base, power) {
var answer;
answer = 1;
var i;
for (i = 1 ; i <= power ; i+= 1) {
answer = answer * base;
}
return answer;
f
then it loops up to the number of power. And i just understand that in the flowgorithm chart but i dont understand the code for it.
what does each section of the for statement mean?
i = 1 to power, i just need help understanding how it is written? What is the 1+= 1 bit?
Thanks.

The exponential function will take in 2 parameters, base and power.
You can create this function and call (fire) it when ever it is needed like so exponential(2,4).
The for (i = 1; 1 <= power; i+=1) is somewhat of an ugly for loop.
for loops traditionaly take three parameters. The first parameter in this case i =1 is the assignment parameter, the next one 1 <= power is the valadation parameter. So if we call the function like so...exponential(2,4) is i less than 4? The next parameter is an increment/decrement parameter. but this doesnt get executed until the code inside the for loop gets executed. Once the code inside the for loop is executed then this variable i adds 1 to itself so it is now 2. This is usefull because once i is no longer less than or equal to power it will exit the for loop. So in the case of exponential(2,4) once the code inside this for loop is ran 5 times it will exit the for loop because 6 > 5.
So if we look at a variable answer, we can see that before this for loop was called answer was equal to 1. After the first iteration of this for loop answer = answer times base. In the case of exponential(2,4) then answer equals 1 times 2, now answer =2. But we have only looped through the foor loop once , and like i said a for loop goes like (assignment, validator, "code inside the foor loop". then back up to increment/decrement). So since we to loop through this for loop 5 times in the case of exponential(2,4) it will look like so.
exponential(2,4)
answer = 1 * 2
now answer = 2
answer = 2 * 2
now answer = 4
answer = 4 * 2
now answer = 8
answer = 8 * 2
now answer = 16
answer = 16 * 2
now answer = 32
So if we could say... var int ans = exponential(2,4)
Then ans would equal 32 hence, the return answer; at the last line of your code.

Related

Removing number from for loop

I have a question about Matlab.
My chunk of code looks like this:
piece = 1:25;
piece([12]) = [];
for sub = 1:(valid_subject)
group_data = [];
for j = 1:length(piece)
group_data = [group_data; subject_data{sub}.trial{j}'];
end
group_mat(:,:,1,sub) = group_data
end
What I want to do is to loop through all trials, from 1 to 25, but omitting trial 12. By using length(piece) I just go through 24 numbers, from 1 to 24. Do you know another way to have numbers from 1 to 25 without 12 as j?
Thank you!
You have modified piece removing 1 item therefore piece now only has 24 elements and you are telling the for loop to follow [1:1:length(piece)]
Instead of for j=1:length(piece) use for j=1:piece

Getting the number of function calls of fminsearch for each iteration

options = optimset('Display','iter','MaxIter',3,'OutputFcn',#outfun);
[x,fval,~,output] = fminsearch(#(param) esm6(param,identi),result(k,1:end-1),options);
This code will find the local Minimum of my esm6 function and due to the 'Display' Option it will Output strings like this
Iteration Func-count min f(x) Procedure
0 1 36.9193
1 5 35.9815 initial simplex
2 7 35.4924 contract inside
3 9 35.4924 contract inside
4 11 33.0085 expand
So in the command window, i get the function Count for each Iteration step. The structure output, which is created by fminsearch has only the total amount of func-count in it. Is there a way to receive all the Information, that is outputed in the command window also in the Output-structure?
EDIT:
I think i'm pretty Close to the solution. I wrote this outputfunction:
function stop = outfun(x,optimvalues,state);
stop = false;
if state == 'iter'
history = evalin('base','history');
history = [history; optimvalues.iteration optimvalues.funcCount];
assignin('base','history',history);
end
end
due to http://de.mathworks.com/help/matlab/math/output-functions.html this should work, but in fact, matlab tells me,
??? Reference to non-existent field 'funcCount'.
any idea, why this happens?

arc4random() and arc4random_uniform() not really random?

I have been using arc4random() and arc4random_uniform() and I always had the feeling that they wasn't exactly random, for example, I was randomly choosing values from an Array but often the values that came out were the same when I generated them multiple times in a row, so today I thought that I would use an Xcode playground to see how these functions are behaving, so I first tests arc4random_uniform to generate a number between 0 and 4, so I used this algorithm :
import Cocoa
var number = 0
for i in 1...20 {
number = Int(arc4random_uniform(5))
}
And I ran it several times, and here is how to values are evolving most of the time :
So as you can see the values are increasing and decreasing repeatedly, and once the values are at the maximum/minimum, they often stay at it during a certain time (see the first screenshot at the 5th step, the value stays at 3 during 6 steps, the problem is that it isn't at all unusual, the function actually behaves in that way most of the time in my tests.
Now, if we look at arc4random(), it's basically the same :
So here are my questions :
Why is this function behaving in this way ?
How to make it more random ?
Thank you.
EDIT :
Finally, I made two experiments that were surprising, the first one with a real dice :
What surprised me is that I wouldn't have said that it was random, since I was seeing the same sort of pattern that as described as non-random for arc4random() & arc4random_uniform(), so as Jean-Baptiste Yunès pointed out, humans aren't good to see if a sequence of numbers is really random.
I also wanted to do a more "scientific" experiment, so I made this algorithm :
import Foundation
var appeared = [0,0,0,0,0,0,0,0,0,0,0]
var numberOfGenerations = 1000
for _ in 1...numberOfGenerations {
let randomNumber = Int(arc4random_uniform(11))
appeared[randomNumber]++
}
for (number,numberOfTimes) in enumerate(appeared) {
println("\(number) appeard \(numberOfTimes) times (\(Double(numberOfGenerations)/Double(numberOfTimes))%)")
}
To see how many times each number appeared, and effectively the numbers are randomly generated, for example, here is one output from the console :
0 appeared 99 times.
1 appeared 97 times.
2 appeared 78 times.
3 appeared 80 times.
4 appeared 87 times.
5 appeared 107 times.
6 appeared 86 times.
7 appeared 97 times.
8 appeared 100 times.
9 appeared 91 times.
10 appeared 78 times.
So it's definitely OK 😊
EDIT #2 : I made again the dice experiment with more rolls, and it's still as surprising to me :
A true random sequence of numbers cannot be generated by an algorithm. They can only produce pseudo-random sequence of numbers (something that looks like a random sequence). So depending on the algorithm chosen, the quality of the "randomness" may vary. The quality of arc4random() sequences is generally considered to have a good randomness.
You cannot analyze the randomness of a sequence visually... Humans are very bad to detect randomness! They tend to find some structure where there is no. Nothing really hurts in your diagrams (except the rare subsequence of 6 three in-a-row, but that is randomness, sometimes unusual things happens). You would be surprised if you had used a dice to generate a sequence and draw its graph. Beware that a sample of only 20 numbers cannot be seriously analyzed against its randomness, your need much bigger samples.
If you need some other kind of randomness, you can try to use /dev/random pseudo-file, which generate a random number each time you read in. The sequence is generated by a mix of algorithms and external physical events that ay happens in your computer.
It depends on what you mean when you say random.
As stated in the comments, true randomness is clumpy. Long strings of repeats or close values are expected.
If this doesn't fit your requirement, then you need to better define your requirement.
Other options could include using a shuffle algorithm to dis-order things in an array, or use an low-discrepancy sequence algorithm to give a equal distribution of values.
I don’t really agree with the idea of humans who are very bad to detect randomness.
Would you be satisfied if you obtain 1-1-2-2-3-3-4-4-5-5-6-6 after throwing 6 couples of dices ? however the dices frequencies are perfect…
This is exactly the problem i’m encountering with arc4random or arc4random_uniform functions.
I’m developing a backgammon application since many years which is based on a neural network trained by word champions players. I DO know that it plays much better than any one but many users think it is cheating. I also have doubts sometimes so I’ve decided to throw all dices by myself…
I’m not satisfied at all with arc4random, even if frequencies are OK.
I always throw a couple of dices and results lead to unacceptable situations, for example : getting five consecutive double dices for the same player, waiting 12 turns (24 dices) until the first 6 occurs.
It is easy to test (C code) :
void randomDices ( int * dice1, int * dice2, int player )
{
( * dice1 ) = arc4random_uniform ( 6 ) ;
( * dice2 ) = arc4random_uniform ( 6 ) ;
// Add to your statistics
[self didRandomDice1:( * dice1 ) dice2:( * dice2 ) forPlayer:player] ;
}
Maybe arc4random doesn’t like to be called twice during a short time…
So I’ve tried several solutions and finally choose this code which runs a second level of randomization after arc4random_uniform :
int CFRandomDice ()
{
int __result = -1 ;
BOOL __found = NO ;
while ( ! __found )
{
// random int big enough but not too big
int __bigint = arc4random_uniform ( 10000 ) ;
// Searching for the first character between '1' and '6'
// in the string version of bigint :
NSString * __bigString = #( __bigint ).stringValue ;
NSInteger __nbcar = __bigString.length ;
NSInteger __i = 0 ;
while ( ( __i < __nbcar ) && ( ! __found ) )
{
unichar __ch = [__bigString characterAtIndex:__i] ;
if ( ( __ch >= '1' ) && ( __ch <= '6' ) )
{
__found = YES ;
__result = __ch - '1' + 1 ;
}
else
{
__i++ ;
}
}
}
return ( __result ) ;
}
This code create a random number with arc4random_uniform ( 10000 ), convert it to string and then searches for the first digit between ‘1’ and ‘6’ in the string.
This appeared to me as a very good way to randomize the dices because :
1/ frequencies are OK (see the statistics hereunder) ;
2/ Exceptional dice sequences occur at exceptional times.
10000 dices test:
----------
Game Stats
----------
HIM :
Total 1 = 3297
Total 2 = 3378
Total 3 = 3303
Total 4 = 3365
Total 5 = 3386
Total 6 = 3271
----------
ME :
Total 1 = 3316
Total 2 = 3289
Total 3 = 3282
Total 4 = 3467
Total 5 = 3236
Total 6 = 3410
----------
HIM doubles = 1623
ME doubles = 1648
Now I’m sure that players won’t complain…

Martin Odersky : Working hard to keep it simple

I was watching the talk given by Martin Odersky as recommended by himself in the coursera scala course and I am quite curious about one aspect of it
var x = 0
async { x = x + 1 }
async { x = x * 2 }
So I get that it can give 2 if if the first statement gets executed first and then the second one:
x = 0;
x = x + 1;
x = x * 2; // this will be x = 2
I get how it can give 1 :
x = 0;
x = x * 2;
x = x + 1 // this will be x = 1
However how can it result 0? Is it possible that the statement don't execute at all?
Sorry for such an easy question but I'm really stuck at it
You need to think about interleaved execution. Remember that the CPU needs to read the value of x before it can work on it. So imagine the following:
Thread 1 reads x (reading 0)
Thread 2 reads x (reading 0)
Thread 1 writes x + 1 (writing 1)
Thread 2 writes x * 2 (writing 0)
I know this has already been answered, but maybe this is still useful:
Think of it as a sequence of atomic operations. The processor is doing one atomic operation at a time.
Here we have the following:
Read x
Write x
Add 1
Multiply 2
The following two sequences are guaranteed to happen in this order "within themselves":
Read x, Add 1, Write x
Read x, Multiply 2, Write x
However, if you are executing them in parallel, the time of execution of each atomic operation relative to any other atomic operation in the other sequence is random i.e. these two sequences interleave.
One of the possible order of execution will produce 0 which is given in the answer by Paul Butcher
Here is an illustration I found on the internet:
Each blue/purple block is one atomic operation, you can see how you can have different results based on the order of the blocks
To solve this problem you can use the keyword "synchronized"
My understanding is that if you mark two blocks of code (e.g. two methods) with synchronized within the same object then each block will own the lock of that object while being executed, so that the other block cannot be executed while the first hasn't finished yet. However, if you have two synchronised blocks in two different objects then they can execute in parallel.

While loop in CoffeeScript

I'm new to CoffeeScript and have been reading the book, The Little Book on CoffeeScript. Here are a few lines from the book's Chapter 2 which confused me while reading :
The only low-level loop that CoffeeScript exposes is the while loop. This has similar behavior to the while loop in pure JavaScript, but has the added advantage that it returns an array of results, i.e. like the Array.prototype.map() function.
num = 6
minstrel = while num -= 1
num + " Brave Sir Robin ran away"
Though it may look good for a CoffeeScript programmer, being a newbie, I'm unable to understand what the code does. Moreover, the words returns an array of results doesn't seem to go together with the fact that while is a loop construct, not a function. So the notion of it returning something seems confusing. Furthermore, the variable num with the string "Brave Sir Robin ran away" in every iteration of the loop seems to be awkward, as the value num is being used as the loop counter.
I would be thankful if you could explain the behavior of the code and perhaps illustrate what the author is trying to convey with simpler examples.
Wow! I didn't know that but it absolutely makes sense if you remember that Coffeescript always returns the last expression of a "block".
So in your case it returns (not via the "return" statement if that is what confuses you) the expression
num + " Brave Sir Robin ran away"
from the block associated with the while condition and as you will return multiple such expressions it pushes them on an array.
Have a look on the generated JavaScript and it might be clearer as the generated code is pretty much procedural
var minstrel, num;
num = 6;
minstrel = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push(num + " Brave Sir Robin ran away");
}
return _results;
})();
I hope that makes sense to you.
Beware, that function call can be very inefficient!
Below is a prime factors generator
'use strict'
exports.generate = (number) ->
return [] if number < 2
primes = []
candidate = 1
while number > 1
candidate++
while number % candidate is 0
primes.push candidate
number /= candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
This is the version using while as expression
'use strict'
exports.generate = (number) ->
return [] if number < 2
candidate = 1
while number > 1
candidate++
primes = while number % candidate is 0
number /= candidate
candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
First version ran my tests in 4 milliseconds, the last one takes 18 milliseconds. I believe the reason is the generated closure which returns the primes.