Using fractional base when summing taylor series causes infinite loop? - c++

I am trying to write a program that will approximate e^x using taylor series as follows:
I created a function that will do the summation, taking in n (number of times to sum) and x (the exponent) and another function that takes in a number and returns its factorial. Pretty simple stuff I think. The problem I'm having is when I input a fractional x first (for instance, .5, 6) the program just hangs. If I first input something like (3, 6) and then after that calculation, I input (.5, 6)I will get an infinite loop. If the x I input is not a fraction, I can do the calculation as many times as I like.
I feel that it must have something to do with my call to the pow() function. I think I'm using it correctly (pow(double, int)) but does it not take fractions or something? I don't understand.
Here's my code:
double taylorSeries (double x, int n, double &error)
{
double sum = 0;
for (int i=0; i <= n; i++)
sum += (pow (x, i))/(factorial (i));
error = (fabs(exp(x) - sum));
return sum;
}
long factorial(int n)
{
long factorial=0;
for (int i = 0; i <= n; i++){
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
return factorial;
}
And then the call to the taylorSeries function in main looks like this:
cout << "please enter x and n: ";
cin >> x >> n;
cout << "taylor series sum = " ;
cout << taylorSeries (x, n, error) << endl;
//cout << "error = " << error;
Can someone help me figure out why this isn't working?

Never mind some of the inefficiencies of your algorithm, the most likely cause for your function seemingly fail to return is a bad parsing of x and thus n not getting set at all, which means it could hold any random value.
Your line:
cin >> x >> n;
If it fails to parse into x properly then it will not attempt to parse the next number because the input stream will be in an error state.
If n has not been initialised it could hold any value which might in reality be an extremely big integer. Thus your algorithm appears not to ever return.
int main()
{
double x = 0.0;
int n = 0;
double error = 0;
cout << "please enter x and n: ";
cin >> x >> n;
if( cin )
{
cout << "taylor series sum, x=" << x << " n=" << n << " : ";
cout << taylorSeries (x, n, error) << endl;
cout << "error = " << error;
}
else
{
cerr << "invalid input" << endl;
}
}
For a more efficient algorithm:
double taylorSeries (double x, int n, double &error)
{
double sum = 1;
double xpow = x; // would start at 1 but we have implemented exponent of 0
double fact = 1;
for (int i=1; i <= n; i++)
{
fact *= i;
sum += xpow / fact;
xpow *= x;
}
error = fabs(exp(x) - sum);
return sum;
}
Your factorial function is technically correct until the point where it will overflow.

Related

How to calculate mean using calling function in C++?

The functions are getInputN(), calculateMean() & displayData().
So to be really clear, these are the requirements.
getInputN function: Should accept the number of the value, N as an integer as argument and ask the user to enter the value of N number. Then, return the sum of the value as a double.
calculateMean function: Should accept the number of the value, N and sum of the value as arguments. Then return the mean as a double.
displayData function: Should accept the mean as argument. Then, display them in the appropriate message on screen. No return value required for this function.
If I run the code, it will display Average = inf
p/s: I'm really sorry for the confusing question at first. I'm really new to this website and this is my very first question. It took me some times to figure out things to ask properly in this platform. I hope you guys understand and once again, sorry for the inconvenience. Thank you for the helps too :)
Here is my code:
#include <iostream>
using namespace std;
int getInputN(int n);
float calculateMean (int n, float sum);
float displayData(double mean);
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN(n);
calculateMean (n, sum);
displayData(mean);
return 0;
}
int getInputN(int n)
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean (int n, float sum)
{
mean = sum/n;
return mean;
}
//function to display the mean
float displayData (double mean)
{
cout << "Average = " << mean;
}
The argument int n in the function getInputN is shadowing (hiding) the global variable n. This prevents the global variable from being updated and sum is divided by zero (the default value of gloval variable without explicit initialization).
If you want to pass data using gloval variables, the arguments should be removed because one of that (n as descrived above) is harmful and other are redundant.
Also the function displayData is declared to return float but didn't execute any return statement. This invokes undefined behavior. I fixed this by changing its return type to void.
#include <iostream>
using namespace std;
int getInputN();
float calculateMean ();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean ();
displayData();
return 0;
}
int getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean ()
{
mean = sum/n;
return mean;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
This fix will make the code work, but there should be better design without usage of global variables. References is useful to have functions modify things given as arguments and std::vector is useful to return "arrays".
The variable n in int getInputN(int n) is used in the function instead of the global n declared. As such, using global n (which is uninitialized till that point initialized to 0) to calculate mean = sum/n will lead to a undefined behavior divide by 0 error, resulting in inf.
More info :
Uninitialized variable behaviour in C++
C++ global and local variables
Also, the function float displayData (double mean) doesn't return any value, causing another undefined behavior.
More info :
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
Modified code :
#include <iostream>
using namespace std;
void getInputN();
void calculateMean();
void displayData();
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN();
calculateMean();
displayData();
return 0;
}
void getInputN()
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
}
//function to calculate the mean
void calculateMean ()
{
mean = sum/n;
}
//function to display the mean
void displayData ()
{
cout << "Average = " << mean;
}
Result :
Enter the numbers of data: 3
1. Enter number: 1
2. Enter number: 3
3. Enter number: 6
Average = 3.33333
Furthermore, if you don't use the numbers for anything else, declaring a float num[50]; is quite pointless. Also, noted that using global variable and using namespace std; is not recommended.
#include <iostream>
const int maxn = 50;
const int minn = 1;
int main()
{
int n; std::cout << "Enter N : "; std::cin >> n;
while (n < minn || n > maxn) {std::cout << "Invalid. Re-enter N : "; std::cin >> n;}
double sum = 0; int tmp;
for (int i = 0; i < n; i++) { std::cout << "Enter number " << i+1 << " : "; std::cin >> tmp; sum += tmp;}
std::cout << "Average : " << sum/n;
}
Result :
Enter N : 3
Enter number 1 : 25
Enter number 2 : 97
Enter number 3 : 111
Average : 77.6667
Knowing how the functions are behaved, we can write implementations that work nicely and don't use any global variables at all.
#include <iostream>
double getInputN(int n);
double calculateMean(int n, double sum);
void displayData(double mean);
int main()
{
//User enter the number of value
int numEntries;
std::cout << "Enter the numbers of data: ";
std::cin >> numEntries;
//if user input more than 50 numbers
while (numEntries > 50 || numEntries <= 0)
{
std::cout << "Invalid! Enter the number in range of (1 to 50)." << std::endl;
std::cout << "Enter the number of data: ";
std::cin >> numEntries;
}
// Get user input
double sum = getInputN(numEntries);
double mean = calculateMean(numEntries, sum);
displayData(mean);
return 0;
}
double getInputN(int n)
{
double sum = 0.;
for (int i = 0; i < n; ++i)
{
double userInput;
std::cout << i + 1 << ". Enter number: ";
std::cin >> userInput;
sum += userInput;
}
return sum;
}
//function to calculate the mean
double calculateMean(int n, double sum)
{
double mean = sum / n;
return mean;
}
//function to display the mean
void displayData(double mean)
{
std::cout << "Average = " << mean;
}
Let's go into some more detail on each of the changes.
First, I've changed the signatures of all of your functions. getInputN is supposed to return a double, not an int. calculateMean is supposed to accept and return a double, not a float. And displayData isn't required to return anything, it doesn't make sense for it to return anything, and therefore I've made its return type void.
Second, note that I've moved the code for figuring out how many entries to enter from getInputN into main. The reason for this is that the sole argument to getInputN is "how many inputs should we get?", so we need to know its value before we call getInputN.
Third, note how I've used the return values from each function in the calling code. In main, when I write double sum = getInputN(numEntries);, that declares a variable sum and stores the return value of getInputN(numEntries) to sum. When you just write getInputN(n);, the return value from getInputN is discarded. By storing it in a variable in main, I can then pass its value to another function, like in the next line where I've written double mean = calculateMean(numEntries, sum);.
Fourth, note how the requirements of the question are such that I no longer use any kind of array whatsoever. getInputN doesn't bother tracking each individual entry, because all we care about is the final sum at the end.

SUM function within for loop, C++

Looking for some insight on how to calculate a sum of user inputted numbers within a for statement and print it after the for loop has been completed.
So far I have this code:
//this code will sort 2 numbers then print them in ascending order and
before exiting, add them all together
// then average them
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z, sort1, sort2;
for (n=0;n<3;n++){
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
if (m>z){
sort1 = z;
sort2 = m;
}
else{
sort1 = m;
sort2 = z;
}
cout << sort1 << sort2 << endl;
}
int sum = m+z;
int sum2 = m+z+sum;
float sum3= m+z+sum2;
cout << " sum of all numbers entered: " << sum << endl;
cout << " average of the numberes entered: " << sum3 /6 << endl;
}
So I know that the sum function i have is incorrect, it only evaluates the last m+z entered by the user and not the others. If i put the sum function in the loop, once it breaks, it dumps all information within the loop rendering the sum value obsolete. Wondering if there's another way to achieve the sum function within the loop but only print once outside the loop.
Are there any other loops that don't delete information within the loop that you can extract outside?
All loops in C++ are scoped, that means that any variables declared within a scope are not accessible outside (of the scope) nor will they persist to the next iteration.
int sum = 0; // declare sum outside of loop
for(int n = 0; 0 < 3; n++)
{
int m, z; // These will be reset every iteration of the for loop
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
/*
Sort and print goes here...
*/
sum += m + z;
}
std::cout << "The sum: " << sum <<std::endl;
#include<iostream>
using namespace std;
int main()
{
int total = 0, i, j, sort1, sort2;
//this For-Loop will loop three times, every time getting two new
//integer from the user
for (int c = 0; c < 3; c++) {
cout << "Enter two integers ( n n ): ";
cin >> i;
cin >> j;
//This will compare if first number is bigger than the second one. If it
//is, then second number is the smallest
if (i > j) {
sort1 = j;
sort2 = i;
}
else {
sort1 = i;
sort2 = j;
}
cout << "The numbers are: " << sort1 << " and " << sort2 << endl;
//This statement will add into the variable total, the sum of both numbers entered before doing another loop around
total += i + j;
}
cout << "The sum of all integers entered is: " << total << endl;
system("pause");
return 0;
}

C++ - Calculating round off error in a sum series program

#include <iostream>
using namespace std;
// on input n returns the value a_n as a double
double term(int n) {
double val = 1.0 / (n+1.0) / (n+1.0);
if (n%2 != 0) val = -val;
return val;
}
/* computes the sum for i from k to k+n-1 of term(i) by the
* direct upwards method */
double direct_up(int k,int n) {
double sum = 0.0;
for (int i=0; i<n; i++) {
sum += term(k+i);
}
return sum;
}
int main() {
cout.precision(16);
int nterms = 0;
int ft = 0;
cout << "Enter first term, number of terms" << endl;
cin >> ft >> nterms;
cout << "The sum of the " << nterms << " terms starting at " << ft << endl;
cout << "direct_up: " << direct_up(ft, nterms) << endl;
return 0;
}
I have created a program which takes a formula and adds term by term starting from the kth term to the (n-1)th term. However I am unable to work out how to calculate the roundoff error after each term?
Would you be able help me with this please?

C++ Compute prime factors of a number and print them

I want to ask the user for an integer, and print the prime factors.
Example: User enters 100, program displays 2 2 5 5
So far I have the following:
#include <iostream>
using namespace std;
void factors(int n){
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
cout << z;
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{cout << n << "\n";}
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
factors(x);
cout << "The result: " << x;
return 0;}
My question is how do I get my main function to communicate with the factors procedure. I run the program, I get the message asking for input, I input 12, I get the message "The result" but with a number of 25, and also 12, the number that the user input. it's like the program is avoiding my factors(int n) procedure. Help with the syntax please?!?
My issue is with the syntax I think.
Because I found the following function to help with listing prime factors:
Finding prime factors
-user44810
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
Thank you!!!
Try this
#include <iostream>
#include <vector>
using namespace std;
vector<int> factors(int n){
vector<int> result;
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
result.push_back(z);
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
result.push_back(z);
return result;
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
vector<int> result_factors = factors(x);
cout << "The result: ";
for (int i: result_factors)
cout << "i ";
cout << endl;
return 0;
}
I changed your factor() function to output nothing on cout but saving the factors in a vector and returning it. In the main function, iterate over the result vector and print the values to cout.
So the biggest issue is that there is a missing brace at the end of your factors function. you need to add another brace after the if (n > 1) brace. Also, there is a missing semicolon at the end of the last cout that will throw an error.
Another issue that won't prevent the code from running is that when you print "The result: " << x you will be giving the same value as the user input.
If you want your main function to print out the result from factors() at that spot, then the function needs to return the data instead of printing it. To fix this, the factors function can be made to return a string with the output you want:
//return a string with the output
string factors(int n){
//create a string to save the output to
string factorlist = "";
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
//append z to the end of the string and add a space to make it easier to read
factorlist+=to_string(z)+" ";
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{
//append n to the end of the string and add a newline
factorlist+=to_string(n)+"\n";
}
//output the string factorlist to wherever the function was called from
return factorlist;
}
then on the lines that look like:
factors(x);
cout << "The result: " << x
Should be:
cout << "The result: " << factors(x);
Currently, you are just printing out the value of x that the user input. If you want to save the value of factors(x) you would need to set a variable equal to it like this:
string FactorsResult = factors(x)
And then print it; or, as in the corrected code above, just print it directly in the cout statement.

C++ Arrays, Array Conversion not working

I've been stuck on a problem for quite a while today, and despite my searching the internet, I'm not sure as to what I should do. This program (that I will post the source code to) is supposed to be based off of the Birthday Paradox, and help us to prove it correct.
The idea is that we have multiple arrays, one of which simulates the paradox by counting the times that there is NOT a matching birthday pair, another which takes that array and creates a ratio(array value/over total iterations) and another that creates a theoretical array ratio value.
Now, this is where I"m stuck. I can get the first two functions to work perfectly, birthdayFrequency and ratioArray, but the next one idealArray I cannot get to work properly. Both ratioArray and idealArray should be a double data type, and ratioArray stores it properly as a double.
However, idealArray does not. It stores the data in the array positions as integers. I want to know if there's something I missed, something that might have caused me to accidentally make the array an integer.
*I'm going to apologize, the code is really long. Also, I can't get it all to fit in a code window. I apologize.
using namespace std;
//Arraytype declarations
typedef int Birthday[365];
typedef bool Counter[365];
typedef double Ratio[365];
void ratioArray(int, Birthday, Ratio);
void idealArray(Ratio);
void outputTable();
int randomInt(int);
//Main function
int main()
{
Birthday array = {0};
Ratio vector = {0};
Ratio matrix = {0};
int seed;
int runs;
//Prompt the user for the number of times the simulation is to be run.
cout << "Hello and welcome to the Birthday Paradox Simulator. " << endl;
cout << "This program uses simulated runs to calculate and verify the paradox." << endl << endl;
cout << "Please enter the number of runs you want done. IMPORTANT, must be a positive integer." << endl;
cin >> runs;
while (runs <= 0)
{
cout << "That's an invalid value. Please enter a positive number." << endl;
cin >> runs;
}
//Prompt the user for a non-negative integer seed value
cout << "Please input a seed to be used for randomly generating numbers. It must be an integer, and non-negative." << endl;
cin >> seed;
while (seed < 0)
{
cout << "I'm sorry, that is an invalid value. Please enter a non-negative number)" << endl;
cin >> seed;
}
//Seed the srand function
srand(seed);
//Call birthdayFrequency function
birthdayFrequency(runs, array);
//Call ratioArray function
ratioArray(runs, array, vector);
//Call idealRatioArray function
idealArray(matrix);
//Testing values
cout << array[1] << endl;
cout << array[2] << endl;
cout << array[3] << endl;
cout << vector[1] << endl;
cout << vector[2] << endl;
cout << vector[3] << endl;
cout << matrix[1] << endl;
cout << matrix[2] << endl;
cout << matrix[3] << endl;
//Call outputTable function
outputTable();
return 0;
}
void birthdayFrequency(int n, Birthday number)
{
int iteration = 0;
int value;
int boundary = 364;
//For loop for n iterations
for ( int k =0 ; k < n ; k++)
{
Counter boolean = {0};
iteration = 0;
//Randomly mark birthdays until there's a duplicate using a for loop
for ( int i = 0; i < 366; i ++)
{
value = randomInt(boundary);
if (boolean[value] == 1)
break;
else
boolean[value] = 1;
number[iteration]++; //Increment the frequency array for every non-match
iteration++;
}
}
}
void ratioArray(int n, Birthday number, Ratio vectors)
{
double ratio;
//For loop for the number of runs, storing the value of ratios to the total number of runs.
for ( int i = 0 ; i < 364 ; i++)
{
ratio = (double)number[i] / n;
vectors[i] = ratio;
}
}
void idealArray(Ratio number)
{
number[0]= 1.0;
number[1] = 1.0;
//Create an ideal, theoretical probability array
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
}
void outputTable()
{
//Not completed yet.
}
int randomInt(int bound)
{
return static_cast<int>( rand() / (RAND_MAX + 1.0) * bound );
}
In this code:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
n is an integer, therefore (1-(n-1)/365)) will evaluate to an integer value, since all values in the expression are integers. Also, an integer multiplied by an integer will produce an integer. Since you start off setting number[1] to 1.0, and each element is calculated by multiplying the previous element by an integer amount, all subsequent values will be integer amounts (although stored as doubles).
Change your code to use doubles for the calculation:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1.0-((double)n-1.0)/365.0));
}