How to get time elapse percentage? - c++

Im trying to get the time elapse percentage, what I do is first check a time interval, them I want to get the percentage of the elapsed time in that time interval, if that makes sense
Here is my code:
if ( ofGetElapsedTimeMillis() > lastTimeCheck + timePeriod ) {
lastTimeCheck = ofGetElapsedTimeMillis();
cout << "its time!" << endl;
}
float p = (float)ofGetElapsedTimeMillis() / (float)(lastTimeCheck + timePeriod);
cout << "time percentage: " << p << endl;
timePeriod = 3000, so every 3 seconds I update the lastTimeCheck variable and the following line of code gets the percentage in that time interval, I get results from 0.5 to 0.9, but I need p to be from 0 to 1
Thanks in advance
- rS

Do you mean the time between lastTimeCheck and lastTimeCheck + timePeriod? That would be
float p = (float)(ofGetElapsedTimeMililis() - lastTimeCheck) / (float)(timePeriod);
You can probably lose one of the float casts too, but I think it's safer and no less readable to leave them in. If you need to guarantee that p is less than or equal to one, though, you should either save and re-use the ofGetTimeElapsedMillis value from the previous call or you should explicitly check p afterwards.
int millisNow = ofGetElapsedTimeMillis();
int millisSinceLastCheck = millisNow - lastTimeCheck;
if (millisSinceLastCheck > timePeriod) {
lastTimeCheck = millisNow;
millisSinceLastCheck = 0;
cout << "it's time!" << endl;
}
float p = (float)(millisSinceLastcheck) / (float)(timePeriod);
cout << "time fraction: " << p << endl;

Related

Add a number to itself in C++

Which is the simplest way to add a number to itself incrementally until some condition is reached? In the code bellow, we can calculate when an event will occur by simply adding event_occurence to itself until we reach max_events. I know it can be done with std::IOTA and vectors, but I want it to keep it to the simplest math possible.
My idea was to use: i=1, i * number to be multiplied, for i<=some value, i++. But only the first value gets incremented correctly.
int main()
{
int curent_year = 2021;
int input_year;
int event_occurence = 4;
std::cout << "When did you watch your first World Cup?" << std::endl;
std::cin >> input_year;
int max_events = (curent_year - input_year) / event_occurence;
int last_event = input_year + (max_events * event_occurence);
int next_first_event = input_year + event_occurence;
std::cout << "Next world cup was held in " << next_first_event << "... Meanwhile, another " << max_events << " world cups took place. The last world cup took place in " << last_event <<"." << std::endl;
int i=1;
int inbetween_events = input_year + i * event_occurence;
for (int i = 1; i <= max_events; i++)
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
code above compiled
int i=1;
int inbetween_events = input_year + i * event_occurence;
for (int i = 1; i <= max_events; i++)
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
Problem 1:
You're using a local variable (counted in CPU registers) with the same name function variable that is the parent of function for (...). You declare it in there by saying "int i = 1", what means "make new temp variable name i, value = 1)
Move the "calc"
int inbetween_events = input_year + i * event_occurence;
inside the function if you want to print out series of numbers (print inbetween_events = input_year + i * event_occurence;) , or make it
for (; i <= max_events; i++)
or
for (i = 1; i <= max_events; i++)
That could work, but I can't test it :P
You could change variables' names, but then it's still pretty ineffective, because you would increment one variable inside a loop, making 2 operations instead of one.
Problem 2:
You also don't increment the "inbetween_events" in the "for" loop.
You ask it to print out that variable "i" times. You initialized that variable as output of arithmetic operation, it wont change its value unless you order it to change it.
C++ doesn't store instructions and run them later when needed. It runs them right away. So, if you want to compute the in-between events at multiple dates, you need to code it this way:
for (int i = 1; i <= max_events; i++)
// compute inbetween_events for each value of i
int inbetween_events = input_year + i * event_occurence;
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
You'll probably want to fix the output with something like:
// output header first
std::cout << "The were also these worlds cups held in the following years: ";
for (int i = 1; i <= max_events; i++)
// compute inbetween_events for each value of i
int inbetween_events = input_year + i * event_occurence;
// output each year with a comma and space
std::cout << inbetween_events << ", ";
}
// end the line
std::cout << std::endl;

implementing riemann sum for the area of a circle

The following code is designed to implement this formula:
void integrate ( double R , double E ) //radius and acceptable error, entered by user
{
int i = 1; //iterator
int n = 1; //number of rectangles
double x = 0;
double width = 0; //stores width of each rectangle
double area = 0; //stores calculated area
double error = E + 1; //stores difference between calculated area and pi*(radius)^2
while ( error > E ) //loop continues as long as error is greater than the acceptable limit entered by user
{
width = R / n; //sets the width of rectangles
area = 0; //with this line, calculated area converges to zero. without it, calculated area increases without bound
while ( i <= n )
{
x = i; //assign iterator value to a separate variable to avoid data type issues in calculation
area += width * sqrt ( pow ( R , 2.0 ) - pow ( width * ( x - 0.5 ) , 2.0 ) ); //riemann integral formula
i++;
}
n++; //increase number of rectangles by 1 to be used in next loop
area *= 4; //forumla uses one quarter of a circle, multiply by 4 to get total area
error = abs ( area - ( pi * pow ( R , 2.0 ) ) ); //error calculation
cout << " \n Calculated area = " << area << "\n" //debugging output
<< " \n Error = " << error << "\n";
cin.get();
}
cout << "\n Area: " << area << "\n" //output to user
<< "\n Error: " << error << "\n"
<< "\n Iterations: " << i << "\n";
return;
}
As the comment says, when the line "area = 0;" is included in the first loop, the area converges to zero, and when it is removed, the area increases without bound. I've been working on this one function for the better part of a week without progress. The rest of the program is completed, tested, and works fine. I have to assume that there's either an error in the logic or the math that I just can't see. Any help would be appreciated.
I hope that the comments are sufficient. I'll provided additional clarification as necessary.
(This is a self-contained function. No other part of the program affects it or is affected by it aside from the user input.)

Newbie error with "expression must have integral or enum type"

Be gentle ... I'm 5 weeks into studying C++. I've dug and dug and cannot figure out why Visual Studio Express (and online compilers) are throwing errors about this.
Note that I've included all my declarations for the sake of clarity -- most are used in different section of code. The line that gets the errors is this one: newsharePrice = perchangeEnd * profitLoss << '\n';
The error I get is c2296, left operand has type double. I have no idea why it doesn't like this ... I multiply other doubles just fine.
double numberShares,
sharePrice,
profitLoss,
profitGain,
commissionPaid,
commissionCost,
sharesCost,
totalshareCost,
newtotalshareCost,
newcommissionCost,
newsharePrice;
double perChange;
double perchangeEnd;
const int minVALUE = 1;
const int maxVALUE = 100;
int seed = time(0);
srand (seed);
perChange = (rand() % (maxVALUE - minVALUE + 1)) + minVALUE;
cout << perChange << '\n';
perchangeEnd = perChange / 100;
int flip = rand() % 2 + 1;
if (flip == 1)
profitLoss = 1;
else
profitLoss = -1;
newsharePrice = perchangeEnd * profitLoss << '\n';
newsharePrice = newsharePrice + sharePrice;
cout << newsharePrice << '\n';
newtotalshareCost = numberShares * newsharePrice;
cout << "You've now paid " << newtotalshareCost << " for your shares." << '\n';
newcommissionCost = newtotalshareCost * commissionRate;
cout << "The new amount of commission for this is " << newcommissionCost << " ." << '/n';
Well, just read the problematic line:
newsharePrice = perchangeEnd * profitLoss << '\n';
// ▲▲▲▲▲▲▲▲
That << '\n' is not part of the multiplication; a copy-pasta fail from your cout lines?
In this context, the compiler has no choice but to assume you're trying to perform a bitwise left-shift operation, which cannot be performed on doubles; only on integers.
While the compilation error is now fixed, your domain error is still there (today is Friday, isn't it?). Why would share price fluctuation affect your commission in any way? You already hace your position. You also measure your number of shares with floating-point precision. While in some cases you might have uneven number of shares, this happens quite seldom. Are you really account for this or just incorrectly use double? Most systmes would count number of shares as integer. Also, you can have negative position, which after all calctulations will give negative commission! Brokers would not agree to that ;). The last, but not the least, in US commission is rarely expressed as percentage of transaction value. It is usually charged in a form of cents per share (or fixed transaction cost for most retail brokers).

Curious division result

How can this code...
vector<double> _pc;
vector<int> _documentClassIds;
[...]
someMemberFunction(vector<int> const & documentIds) {
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
cout << "documentIds.size() = " << documentIds.size()<<endl;
// Normalize
for (auto documentId : documentIds)
_pc[_documentClassIds[documentId]] =
_pc[_documentClassIds[documentId]] / documentIds.size();
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
}
produce this output?
_pc[0] = 3
_pc[1] = 3
documentIds.size() = 6
_pc[0] = 0.0138889
_pc[1] = 0.0138889
I'm not sure what you think the problem is.
You have six document IDs, so your for loop runs six times. Each time it runs, it divides one of your _pc array values by six.
Since 0.0138888... is 3 divided by 216 (6^3), the calculations seem correct.
It's obvious that the selection of which _pc array entry to divide is equally distibuted so that each gets divided three times, so each ends up as:
(((3 / 6) / 6) / 6) => 0.013888...

Why isn't this operation giving me greater precision?

I'm estimating the value of Pi using the following formula:
Using the following C++ code:
double sub = 0;
int prec = 1000; //How many iterations to use in estimate.
for(int i = 1; i <= prec; i++){
double frac = 1/((3+(2*(i-1))) * pow(3, i));
sub += (i == 1) ? 1-frac : (i%2) ? -frac : frac;
}
double pi = sqrt(12)*sub;
cout << "Pi estimated with precision of " << prec << " iterations is " << pi << ".\n";
My problem is that even at 1000 (or 100000 for that matter) iterations, the highest precision I'm getting is 3.14159. I've tried using static_cast<double>() on each of the numbers in the calculation but still get the same result. Am I doing something wrong here, or is this the max precision this method will yield? I'm new to C++, but not to programming.
the problem is you don't print all the precisions. you need to call,
std::cout << std::setprecision(10) << ...