Trouble with output function C++ - c++

I am having trouble getting this program to output properly. It simulates a drunken sailor on a board that randomly goes one step to the left or right. At the end of the simulation, the program outputs the percentage of times he fell off the board vs not falling off. My percentage is always zero, and I can't figure out whats wrong with my code.
This function correctly outputs the "experiments" and "fallCount" variable, but always displays "fallCount / experiments" as zero.
This should read "After 2 experiments, sailor fell 1 time, fall percentage was 0.5%"
(if experiments = 2 and fallCount = 1) instead, its 0% every time.
Let me know what I am doing wrong. Thank you!
void outputExperimentStats(int experiments, int fallCount)
{
cout << "After " << experiments << " experiments, sailor fell "
<< fallCount << " time, fall percentage was " << fallCount / experiments << "%\n";
}

That is because you are using integer division. There are no decimals, so things get truncated. E.g.
1 / 2 --> 0 // integer division
This is correct, and expected behavior.
To get the behavior you want, use double or float.
1.0 / 2.0 --> 0.5 // double division
In your example, you can either change the types of your inputs to double or if you want to keep them int, you can convert them during the division
static_cast<double>(fallCount) / static_cast<double>(experiments)

Related

Variable changing unseen

I'm (trying to) write a program that's a sort of simplified neural net, where offby is my function to measure how close to the goal value the neural net gets on this iteration. It seems to be working completely fine except for the fact that (seemingly randomly) it sometimes assigns a negative value to offby.
The only block of code where offby can change is (aside from setting it back to 0 at the start of every iteration):
offby = offby + std::abs((sigmoid(outcome[k]) - goal));
After that bit of code I have it output the offby value, and it's working fine. Then I have the bit of code below (where it changes the value of one of the connections in the net).
std::cout << "Offby is before 5: " << offby << "\n";
std::uniform_int_distribution<int> which_unit(0, unitsinlayer3);
std::uniform_int_distribution<int> which_connection(0, unitsinlayer4);
one = which_unit(rng);
two = which_connection(rng);
thirdtofourth[one][two] = +mutateby;
std::cout << "Offby is after 5: " << offby << "\n";
At "offby is before 5" it still outputs the correct value, then at "offby is after 5" it sometimes outputs a negative value. There is literally no other code in between, the only reason I've even figured out it's this part of the code that assigns a negative value somehow is through having it output offby at practically every bit of code and seeing where it changes.
Now I might be missing something completely obvious, but how come changing these other variables might change my offby value?
In case this is relevant, mutateby is assigned as follows (earlier in the code)
std::normal_distribution<double> mutation(0, 0.1);
double mutateby = mutation(rng);
Just as an example, this just happened when I ran the program:
Offby is before 5: 0.000000
Offby is after 5: -0.056328
Any help would be much appreciated.
Edit: Turns out that it changes specifically in this line:
thirdtofourth[one][two] = +mutateby;

Comma initialization and Constructors C++ and Eigen

I'm using Eigen library in C++ and I'm trying to find the determinant of a matrix. I'm getting different results depending on how I initialize the matrices.
Method I:
MatrixXd a(3, 3);
for (int n = 0; n < 3; n++)
for (int m = 0; m < 3; m++)
a(n,m) = (double) (n + m*m + 2.5)/3;
cout << "Matrix a: " << endl;
cout << a << endl;
cout << "Determinat of matrix a is: " << a.determinant() << endl;
This part of the code prints
Matrix a:
0.8333333 1.166667 2.166667
1.166667 1.5 2.5
1.5 1.833333 2.833333
Determinat of matrix a is: -7.401487e-17
Method II:
MatrixXd b(3, 3);
b << 0.8333333, 1.166667, 2.166667,
1.166667, 1.5, 2.5,
1.5, 1.833333, 2.833333;
cout << b;
cout << endl << "Determinant of matrix b is: " << b.determinant();
which prints
0.8333333 1.166667 2.166667
1.166667 1.5 2.5
1.5 1.833333 2.833333
Determinant of matrix b is: 2.333331e-07
Method I produces the wrong result while Method II gives the right answer. What's going wrong in the first case? (I'm using Visual Studio.) Thanks in advance!
What you are observing here are rounding errors in your calculations. Let me explain it like this:
For a computer, everything is based on the binary number system, i.e. instead of base 10 like we mostly use in our everyday lives, computers calculate with base 2, i.e. only the digits 0 and 1.
This not only applies to integers, but also to real numbers like 0.83333...
But just like it is impossible to write all digits of 0.83333..., your computer cannot store every last digit of the binary representation of this number - thus it has to round the result somehow.
Depending on how you initialize it (either by computing (n + m*m + 2.5)/3 or by reading the value from your comma-initialization), the result might be slightly different in one of the last digits, thus leading to different results.
You can try this out by comparing 0.8333333 with 2.5/3, which will probably return false. If you print the numbers, you get the same result, but the internal representation differs ever so slightly.
However you should note that the absolute error itself is quite small (smaller than 0.000001), so you don't need to worry about it at the moment.
If you want exact results, it might be helpful to switch to a rational number type which can represent these values exactly.

finding the big oh estimate of the a simple print function

while (num > 1)
{
cout << "num is now " << num << endl;
cout << "hello // \n";
num /= 2;
}
I am trying to give the big O estimate for the print statements.
The user gets to input num. I tried a few inputs and am starting to see a pattern.
1 gives 0 print.
2-3 gives 1 print.
4-7 gives 2 prints.
8-15 gives 3 prints.
16-31 gives 4 prints.
let p = the number of prints. I see that the range of numbers giving you a certain amount of prints is 2^p.
So is the big O estimate 2^p ?
You are definitely thinking in the right direction and what is more important - you are approaching the problem in the correct manner. Still your final conclusion is a bit off the target. Try to use 2p for the values you've computed and you will see that the number of prints is not 2p, but rather the inverse of this function.
It's O(log N). The reason is that your halving the range with each iteration. If you're familar with binary search then your loop if doing something similar.
You've correctly observed the 2^p pattern. The inverse of this is log base-2 (rather than log base-10). When people mention log in big-O notation they typically mean the base-2 version.
just use the master theorem.
Link here
b = 2 f(n) = 1 a = 1.

How would I implement a FCFS processor scheduling simulator?

I have a vector of structs, with the structs looking like this:
struct myData{
int ID;
int arrivalTime;
int burstTime;
};
After populating my vector with this data:
1 5 16
4 7 12
3 12 4
2 7 8
where each row is an individual struct's ID (arbitrary, doesn't denote order of arrival), arrivalTime and burstTime, how would I use "for" or "while" loops to step through my vector's indices and calculate the data in a way that I could print something like this out?
Time 0 Processor is Idle
Time 5 Process 1 starts running
Time 21 Process 2 is running
Time 29 Process 4 is running
Time 41 Process 3 is running
The way I thought I could do it was to have an integer keep track what the current time is (the current time being the sum of the burst times of processes that have already ran) but I can't seem to figure out an algorithm that accounts for Idle time (when the processor is not doing anything and a new task hasn't arrived yet) as well as keeping track of the other numbers as well. For simplicity's sake I just decided that when two processes arrive at the same time I would process the one with the lower ID number. I know I didn't put much code here to demonstrate what I'm trying to do, but I hope I've explained it fairly clearly. I'm looking for a psuedo-code algorithm solution to this problem, but I wouldn't say no to something that has been coded (In C++?).
As an additional note, in case I wasn't able to convey how I access my data clearly, this:
cout << structVector[0].ID << "\n";
cout << structVector[0].arrivalTime << "\n";
cout << structVector[0].burstTime << "\n";
would print out
1
5
16
Any help in psuedo-code or actual code would be GREATLY appreciated!!! After reading this post over a few times I realize I've been pretty generic with the question, but I would love some help just understanding how to calculate this data.
First, sort the vector based on arrival times.
Then the following code will accomplish what you are looking for.
int i = 0, time = 0;
while (i < vec.size())
{
if (vec[i]. arrivalTime > time)
cout << "Time " << time << "process is idle";
time += vec[i].arrivalTime;
cout << "Time " << time << " Process " << vec[i].ID << " is running" << endl;
time += vec[i].burstTime;
i++;
}

Timing a function in microseconds

Hey guys I'm trying to time some search functions I wrote in microseconds, and it needs to take long enough to get it to show 2 significant digits. I wrote this code to time my search function but it seems to go too fast. I always end up getting 0 microseconds unless I run the search 5 times then I get 1,000,000 microseconds. I'm wondering if I did my math wrong to get the time in micro seconds, or if there's some kind of formatting function I can use to force it to display two sig figs?
clock_t start = clock();
index = sequentialSearch.Sequential(TO_SEARCH);
index = sequentialSearch.Sequential(TO_SEARCH);
clock_t stop = clock();
cout << "number found at index " << index << endl;
int time = (stop - start)/CLOCKS_PER_SEC;
time = time * SEC_TO_MICRO;
cout << "time to search = " << time<< endl;
You are using integer division on this line:
int time = (stop - start)/CLOCKS_PER_SEC;
I suggest using a double or float type, and you'll likely need to cast the components of the division.
Use QueryPerformanceCounter and QueryPerformanceFrequency, assuming your on windows platform
here a link to ms KB How To Use QueryPerformanceCounter to Time Code