A tabulation program on a given interval [a;b] with step c - c++

I developed a program to tabulate a given interval [a;b] with a step of c, and also find its largest and smallest value on this interval. I'm not sure if I have it right, so I wanted some advice. This code has a picture with a task condition.enter image description here
In the process of solving the given problem, apply the loop operator with a prerequisite. In the process of implementing the given task, assume that the argument of the function is identified as x, and the identifier of the variable responsible for the value of the function is y.
#include <iostream>
#include <math.h>
#include <clocale>
#define _USE_MATH_DEFINES
#include <iomanip>
#include<climits>
using namespace std;
int main(){
setlocale(LC_CTYPE, "");
double x, y, a, b, c;
double max, min, max_y, min_y;
max = -INT_MAX;
min = INT_MAX;
cout << "\n a:";
cin >> a;
cout << "\n b:";
cin >> b;
cout << "\n c:";
cin >> c;
cout << "\n a = " << a;
cout << " b = " << b;
cout << " c = " << c;
y = a;
while(y <= b){
if(y > 1) x = sin(sqrt(y + log(y)));
if((0 <= y) && (y <= 1)) x = M_PI + pow(cos(y + 1.2), 2);
if(y < 0) x = y * log10(pow(y,2) +2) + M_PI;
if(x > max){
max = x;
max_y = y;
}
if(x < min){
min = x;
min_y = y;
}
cout << "\n x = " << setw(8) << x << " y = " << setw(8) << y;
y += c;
}
cout << "\n The largest value in the given interval is" << max << " at y = " << max_y << "\n";
cout << "\n The smallest value in the given interval is" << min << " at y = " << min_y << "\n";
return 0;
}
When entering the values a,b,c into the console, our program should tabulate the function (output to the console) and find the smallest and largest value in the interval. I have the program working, but I'm not sure if it's correct. I would like to hear some advice

Added small updates:
Looks good overal
#include <iostream>
#include <cmath> //math.h == cmath
#include <clocale>
#define _USE_MATH_DEFINES
#include <iomanip>
#include<climits>
using namespace std;
void tabulate(double from, double to, double step)
{
double max, min, max_y, min_y, x = 0;
max = from; //they all start at 'from' anyway, its always best to set the max and min to first element of the array you're going through. They get overwritten anyway.
min = from;
for(double y = from; y < to; y += step)
{
if(y > 1) x = sin(sqrt(y + log(y)));
if((0 <= y) && (y <= 1)) x = M_PI + pow(cos(y + 1.2), 2);
if(y < 0) x = y * log10(pow(y,2) +2) + M_PI;
if(x > max){
max = x;
max_y = y;
}
if(x < min){
min = x;
min_y = y;
}
cout << " x = " << setw(8) << x << " y = " << setw(8) << y << endl;
}
cout << "The largest value in the given interval is " << max << " at y = " << max_y << endl;
cout << "The smallest value in the given interval is " << min << " at y = " << min_y << endl;
}
int main(){
setlocale(LC_CTYPE, "");
double a,b,c;
cout << "a: ";
cin >> a;
cout << "b: ";
cin >> b;
cout << "c: ";
cin >> c;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
tabulate(a,b,c);
return 0;
}

Related

C++ always returns -inf when calculating cosine

I am attempting to write a function that takes a value x and calculates the cos x by the series expansion, I'm always getting -inf, indifferent which value is read in.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int fac(int n){
return n == 0 || n == 1 ? 1 : n * fac(n-1);
}
int main(){
double eps = 1e-15;
double x;
cin >> x;
long double ak = 1, sn = 0;
for(int k=1; abs(ak) > eps * abs(sn); k++){
double sgn = k % 2 == 0 ? 1 : -1;
sn += ak;
ak = sgn * pow(x, 2 * k) / fac(2*k);
}
cout << setprecision(4) << setw(5) << "x" << setprecision(15) << setw(20) << "cos x" << endl;
cout << setprecision(4) << setw(5)<< x << " " << setprecision(15) << setw(20) << sn << endl;
cout << setw(26) << cos(x) << endl;
return 0;
}
I debugged the code and at a certain point ak gets -inf. But why?

How to print the and update the scoreboard on the same line here?

#include <iostream>
#include <cstdlib>
#include <iomanip>
int Human_Roll() {
int num1;
srand(time(0));
num1 = (1 + rand() % 6);
return num1;
}
int Human_Roll_2() {
int num2;
num2 = (1 + rand() % 6);
return num2;
}
int Computer_Roll() {
int num3;
num3 = (1 + rand() % 6);
return num3;
}
int Coumputer_Roll_2() {
int num4;
num4 = (1 + rand() % 6);
return num4;
}
int main() {
int counter1 = 0, counter2 = 0;
char start;
for (int i = 1; i <= 150; i++) {
std::cin >> start;
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << " Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
}
This is a supposed to be a dice game that calculates the sum of two randomly generated sides of the 6 sided dices. It does it two times and compares the sums to pick the winner with the bigger sum, and it should print out the scoreline every time the the winner is declared. My question is, how can I make the scoreline be updated on the same line as the game continues and not print "scoreboard x - y " every time the round is finished?
Hi from what I' m understanding you want o clear the console like this std::cout << "\033[2J\033[1;1H"; so when you roll the dices again the code comes in the same place but before you do this you need to stop the console make it wait for input and say something like "Press enter to play again" then the console clears and the next game comes in the same place or you can use something like Sleep(milliseconds); before cleaning.
Hope this is what you looking for.
As #enhzflep said this will end up being more than complicated solution for the system dependent code.
However the easy and quick solution is for visually having the same line being updated is to create many empty lines for every for loop iteration.
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
As i said earlier this is the best c++ could do when there is no system information available. Using the standard commands.
updated for loop would look like
for (int i = 1; i <= 150; i++) {
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << " ----- Game " << i << " -----";
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << "---------------------------------------------"
std::cout << "Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
}
There are other ways to do it such as
Sysetm call to clear the terminal
but this method not safe why
The standard way to print end lines
Using the curser library #include <curses.h>
Advantage it is a cross-platform but can not be mixed with standard I/O

How do I print addition details on C++?

For example, If i am printing a sum of numbers to the screen, but also need to print the addition details.
example:
cout << "Sum of the values from " << y << " to " << x << " is: " << sum ;
this only displays the sum but i need it to display as 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20.
How do i get it to print the addition details?
I have already tried using different formulas to find the sum and the sum formulas work. All I need to know is how to print the addition details to the screen.
#include <iostream>
using namespace std;
int main()
{
int x, y, sum;
sum = 0;
cout << "Input two integers: ";
cin >> x >> y;
for (int i = y ; i <= x; i++)
{
sum += i;
}
for (int i = x; i <= y; i++)
{
sum = sum + i;
}
for ( int i = x; i == y; i++)
{
sum = i;
}
if ( x > y)
{
cout << "Sum of the values from " << y << " to " << x << " is: " << sum ;
}
else if ( y > x)
{
cout << "Sum of the values from " << x << " to " << y << " is: " << sum;
}
else if ( x == y)
{
cout << "Sum of the values from " << x << " to " << y << " is: " << sum;
}
return 0;
}
Here is my code.

Calculation after the for loop is incorrect (C++)

The code I am currently working on is a random walker. The code represents a person taking a step in any random direction (up,down,left,right), then the new location is printed out respectively. In the beginning the user is prompted to enter any amount of steps or how many times the loop should be iterated. The goal of the code is to calculate the squared distance between (0,0)initial and (x,y)final. The distance should be equal to (xx)+(yy) because the initial position that would normally be subtracted is (0,0). The issue or semantic issue I am running into is with the distance calculation. The calculation is not always using the correct x or y value. For example if the final location was (0,-4), somehow x = -1, therefore the distance equals 17 instead of 16. This first example is in image 1. Image 2 is another run for the code. Any help or tips would be greatly appreciated, here is the code:
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
for(int i = 0; i <= N; i++) {
cout << "(" << x << ", " << y << ")" << endl;
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
}
int d = (x*x)+(y*y);
cout << "the distance equals: " << d << endl;
cout << endl;
cout << "x equals before: "<< x << endl;
x = (pow(x,2));
cout << "x equals after squaring: "<< x << endl;
cout << endl;
cout <<"y equals before: " << y << endl;
y = (pow(y,2));
int sum = x + y;
cout <<"y equals after squaring: " << y << endl;
cout << endl;
cout << "x+y after squaring equals: " << sum << endl;
}
for(int i = 0; i <= N; i++)
Since you are starting from 0, the condition should be i < N.
Next issue, is int d = (x*x)+(y*y); The distance formula is
So the initialization should be
int d = sqrt((x * x) + (y * y));
Also what is the point of squaring the x and y values at the end?
You are printing the position BEFORE it is changed based on the value of r. So the last value that's printed out is not the actual final value of x and y, but the one of one step earlier. That's why you're getting unexpected distance.
Sorry for the delayed response, I figured out what I had to do. The object of the assignment was to print out each location and find the squared distance at the end of the loop. Here was the solution for anyone interested.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
cout << "(" << x << ", " << y << ")" << endl;
for(int i = 1; i <= N; i++) {
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
cout << "(" << x << ", " << y << ")" << endl;
}
x = (pow(x,2));
y = (pow(y,2));
int squaredDistance = x + y;
cout << "The squared distance is " << squaredDistance << endl;
}

Issue with Box Muller Transform when implementing a Normal Distribution PRNG

Using a Linear Congruent Generator I am able to create two independent Pseudo-Random number sequences which are uniformly distributed. I am trying to alter my program to allow it to use these sequences and perform a Box-Muller transform to change them into a normally distributed set.
The issue I am having however is that my new "normally distributed random number" (Z) is always equal to zero regardless of the input seed values for the two uniform sequences.
Any tips would be gratefully appreciated.
Many Thanks
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
#define M 4294967295
unsigned long get_rand(unsigned long x) //establishing function to generate random numbers
{
unsigned long a = 2269477;
unsigned long b = 1; //Values taken from wikipedia for Linear Congruence Method
unsigned long m = M;
unsigned long y;
y = (a * x + b) % m;
return y;
}
unsigned long get_normal(unsigned long x1, unsigned long x2)
{
unsigned long R;
unsigned long phi;
unsigned long u;
R = sqrt(-2 * log(x1)); //Box-Muller Transform
phi = (2 * M_PI*x2);
u = R*cos(phi);
return u;
}
double u1, u2, Z;
double bin0 = 0;
double bin1 = 0;
double bin2 = 0; //Variables used to store frequency of each number range
double bin3 = 0;
double bin4 = 0;
double bin5 = 0;
double bin6 = 0;
double bin7 = 0;
double bin8 = 0;
double bin9 = 0;
int main() {
double seed1,seed2;
cout << "Please enter seed values " << endl;
cin >> seed1;
cout << "\n";
cin >> seed2;
double x;
cout << "Please enter how many random numbers you want " << endl;
cin >> x;
cout << endl;
cout << "Random Numbers generated shown below: " << endl;
for (int i = 0; i < x; i++) //generate as many random numbers as the user has asked for
{
seed1 = get_rand(seed1);
seed2 = get_rand(seed2);
u1 = (double(seed1) / M); //changing to double and dividing by 'M' gets all values between 0 and 1
cout <<"U1 = " << u1 << endl; //type conversion to prevent integer rounding in division
u2 = (double(seed2) / M);
cout << "U2 = " << u2 << endl;
Z = get_normal(u1, u2);
cout <<"Z = " << Z << endl;
if (Z >= 0.0 && Z <= 0.1)
{ //checking for which intervals each random number falls into
bin0++; //if a number falls into this interval, increment the counter by 1 each time
}
else if (Z > 0.1 && Z <= 0.2) //if it doesnt fall into first interval, it will check the next interval, and so on...
{
bin1++;
}
else if (Z > 0.2 && Z <= 0.3)
{
bin2++;
}
else if (Z > 0.3 && Z <= 0.4)
{
bin3++;
}
else if (Z > 0.4 && Z <= 0.5)
{
bin4++;
}
else if (Z > 0.5 && Z <= 0.6)
{
bin5++;
}
else if (Z > 0.6 && Z <= 0.7)
{
bin6++;
}
else if (Z > 0.7 && Z <= 0.8)
{
bin7++;
}
else if (Z > 0.8 && Z <= 0.9)
{
bin8++;
}
else if (Z > 0.9 && Z <= 1.0)
{
bin9++;
}
}
double binTotal = bin0 + bin1 + bin2 + bin3 + bin4 + bin5 + bin6 + bin7 + bin8 + bin9;
cout << endl;
int bin0Percent = (bin0 / binTotal) * 100; //working out a percentage
cout << " Number of values in range 0.0-0.1: " << bin0 << endl; //output screen for each interval
cout << " Percentage of values in this interval: " << bin0Percent << "%" << endl;
cout << endl;
int bin1Percent = (bin1 / binTotal) * 100;
cout << " Number of values in range 0.1-0.2: " << bin1 << endl;
cout << " Percentage of values in this interval: " << bin1Percent << "%" << endl;
cout << endl;
int bin2Percent = (bin2 / binTotal) * 100;
cout << " Number of values in range 0.2-0.3: " << bin2 << endl;
cout << " Percentage of values in this interval: " << bin2Percent << "%" << endl;
cout << endl;
int bin3Percent = (bin3 / binTotal) * 100;
cout << " Number of values in range 0.3-0.4: " << bin3 << endl;
cout << " Percentage of values in this interval: " << bin3Percent << "%" << endl;
cout << endl;
int bin4Percent = (bin4 / binTotal) * 100;
cout << " Number of values in range 0.4-0.5: " << bin4 << endl;
cout << " Percentage of values in this interval: " << bin4Percent << "%" << endl;
cout << endl;
int bin5Percent = (bin5 / binTotal) * 100;
cout << " Number of values in range 0.5-0.6: " << bin5 << endl;
cout << " Percentage of values in this interval: " << bin5Percent << "%" << endl;
cout << endl;
int bin6Percent = (bin6 / binTotal) * 100;
cout << " Number of values in range 0.6-0.7: " << bin6 << endl;
cout << " Percentage of values in this interval: " << bin6Percent << "%" << endl;
cout << endl;
int bin7Percent = (bin7 / binTotal) * 100;
cout << " Number of values in range 0.7-0.8: " << bin7 << endl;
cout << " Percentage of values in this interval: " << bin7Percent << "%" << endl;
cout << endl;
int bin8Percent = (bin8 / binTotal) * 100;
cout << " Number of values in range 0.8-0.9: " << bin8 << endl;
cout << " Percentage of values in this interval: " << bin8Percent << "%" << endl;
cout << endl;
int bin9Percent = (bin9 / binTotal) * 100;
cout << " Number of values in range 0.9-1.0: " << bin9 << endl;
cout << " Percentage of values in this interval: " << bin9Percent << "%" << endl;
cout << endl;
}
get_normal returns a long, which cannot be between 0 and 1, since it is an integer. Storing the integer returned by the function into a double (Z) does not magically restore the discarded fractional part.
I think you should use floating point arithmetic (that is, doubles) in get_normal, and also change the return type.
By the way, the C++ standard library has lots of random number distributions. You might want to use it instead of trying to write your own.
M is too big, in the limit of a long. So any long divided (or modulus) by this M will result in 0. Perphaps you should use unsigned long long.
Also:
Instead of R = sqrt(-2 * log(x1)); try R= sqrt(fabs(2 * log(x1)));
Also
phi = (2 * M_PI*x2);
u = R*cos(phi);
phi is always an multiple of 2*PI, so cos(phi)= 1.