I am using Visual Studios 2015, and I ran into a problem. Run-Time Check Failure #2 - Stack around the variable 'myArray' was corrupted. I am not sure where in the program that could cause some sort of corruption to my array. But when I did calculations involving manipulating the array, several numbers turned to 0.0000 instead of what they were originally. Could someone help?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double xmin, xmax;
const int POINTS = 20;
const double PI = 3.1416;
double increments;
double range, mean;
double total = 0;
double myArray[POINTS];
double number = myArray[0];
double mode = number;
int count = 1;
int countMode = 1;
cout << "Enter in a value for the minimum x value: ";
cin >> xmin;
cout << "Enter in a value for the maximum x value: ";
cin >> xmax;
if (xmin < 0)
increments = (abs(xmin) + xmax) / POINTS;
else
increments = (xmax - xmin) / POINTS;
int i = 0;
double x = xmin + increments * i;
double minimum = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
double maximum = myArray[19];
cout << setw(15) << "x |" << setw(15) << "f(x)" << endl;
cout << setw(32) << setfill('-') << " " << endl;
cout << setfill(' ');
for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
x = xmin + increments * i;
cout << fixed << showpos << setw(15) << setprecision(2) << x << setw(15) << setprecision(4) << myArray[i] << endl;
if (myArray[i] <= minimum)
minimum = myArray[i];
if (myArray[i] > maximum)
maximum = myArray[i];
}
cout << endl;
range = maximum - minimum;
for (int count = 0; count <= POINTS; count++)
{
total += myArray[count];
}
mean = total / POINTS;
int temp;
bool swap;
do
{
swap = false;
for (int i = 0; i < POINTS - 1; i++)
{
if (myArray[i] > myArray[i + 1])
{
temp = myArray[i];
myArray[i] = myArray[i + 1];
myArray[i + 1] = temp;
swap = true;
}
}
} while (swap);
for (int i = 0; i <= POINTS; i++)
{
if (myArray[i] == number)
{
count++;
}
else
{
if (count > countMode)
{
countMode = count;
mode = number;
}
count = 1;
number = myArray[i];
}
}
cout << "The maximum value is: " << maximum << endl;
cout << "The minimum value is: " << minimum << endl;
cout << "The range is: " << range << endl;
cout << "The mean value is: " << mean << endl;
cout << "The median value is: " << (myArray[9] + myArray[10]) / 2 << endl;
cout << "The mode value is: " << mode << endl;
for (i = 0; i <= POINTS; i++)
cout << myArray[i] << endl;
system("pause");
return 0;
}
double myArray[POINTS];
myArray is an array of 20 doubles - myArray[0] through myArray[19].
for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
This sets myArray[0] through myArray[20]. Accessing myArray[20] is a not allowed, because that is the 21st element of a 20-element array.
Note that the compiler won't always be nice enough to detect this problem for you. Visual C++ is doing you a favour here by causing the program to crash, believe it or not.
Related
Hi I wrote a short program to try to answer Google Kickstart 2020 Round B problem Wandering Robot. I essentially tried to implement the analysis provided by Google, and my solution seems to work on all the sample cases I've tried, but it never passes Google's first test set.
Here's my code, and below it the problem description and a short explanation of my approach. What I really want to know is what I'm doing wrong, why I'm not passing the first test set, more than anything.
#include <iostream>
#include<math.h>
using namespace std;
#include <iomanip>
int W, H, L, U, R, D;
const int len = 100000;
double facts [len];
void factorial(){
facts[0] = log2(1);
for(int i=2; i<= len; i++){
facts[i-1] = log2(i) + facts[i-2];
}
}
bool impossible(){
if((L==1 && R==W) || (U==1 && D==H)){
return true;
}
return false;
}
double pass(int x, int y, int s, int t, int i){
double num = log2(x+y);
num = facts[x+y-1];
double prob = x+y;
double tot = 0;
double comb = 0;
//cout << x << " " << s << " " << y << " " << t << endl;
while(x!=s && y!=t){
double denom = facts[x-1] + facts[y-1];
comb = num - denom - prob;
// cout << num << endl;
tot += pow(2, comb);
x+=i;
y-=i;
}
//lower diagonal, hit the bottom
//x+1 = number of moves it takes
//to hit last square
if(y==H){
double p = pow(2,comb);
tot -= p;
x-=i;
for(int j=1; j<=x; j++){
p -= pow(0.5, prob);
p += pow(0.5, prob-j-1);
}
tot += p;
}
//upper diagonal, hit the right side
else if(x==W){
double p = pow(2,comb);
tot -= pow(2, comb);
y+=i;
for(int j=1; j<=y; j++){
p -= pow(0.5, prob);
p += pow(0.5, prob-j-1);
}
tot += p;
}
return tot;
}
int main() {
int t;
cin >> t; // read t. cin knows that t is an int, so it reads it as such.
for (int i = 1; i <= t; ++i) {
cin >> W >> H >> L >> U >> R >> D;
double tot = 0;
if(impossible()){
cout << "Case #" << i << ": 0.0" << endl;
}
//upper diagonal
else if(L==1 || D==H){
factorial();
tot = pass(R, U-2, W, -1, 1);
cout << "Case #" << i << ": " << fixed << setprecision(9) << tot << endl;
}
//lower diagonal
else if(R==W || U==1){
factorial();
tot = pass(L-2, D, -1, H, -1);
cout << "Case #" << i << ": " << fixed << setprecision(9) << tot << endl;
}
//symmetric
else if(D==R && L==U){
factorial();
tot = pass(R, U-2, W, -1, 1);
tot *=2;
cout << "Case #" << i << ": " << fixed << setprecision(9) << tot << endl;
}
//call count both
else{
factorial();
tot = pass(R, U-2, W, -1, 1);
tot += pass(L-2, D,-1, H, -1);
cout << "Case #" << i << ": " << fixed << setprecision(9) << tot << endl;
}
}
return 0;
}
The way that I tried to solve it was to find the probability of passing through the green squares and the reciprocal squares spanning from the upper right corner of the hole to the right edge of the arena.
I am trying to produce this code but have and error in the double functions starting at double b[n];. The error I am getting is saying that "the expression must have a constant value, the variable 'n' can not be used as a constant. Any help you can give would be much appreciated.
//Get inputs from user
double V = 0; // shear load applied
int n;
double H_total = 0;
double A_total = 0;
double a = 0;
double I = 0;
double t = 0;
double e = 0;
double y_bar = 0;
cout << "Input the shear load applied in [N]: " << endl;
cin >> V;
cout << "Input number of sections: " << endl;
cin >> n;
double b[n];
double h[n];
double A[n];
double y[n];
double Q[n];
double Tau[n];
for (int i = 1; i <= n; i++) { // Calculates variables to find shear stress
cout << "Width of section " << i << " in [mm]: " << endl;
cin >> b[i];
cout << "Height of section " << i << " in [mm]: " << endl;
cin >> h[i];
H_total += h[i];
A[i] = b[i] * h[i];
A_total += A[i];
y[i] = H_total - 0.5 * h[i];
a += A[i] * y[i];
y_bar = a / A_total;
}
cout << "Applied shear force, V = " << V / 1000 << " kN" << endl;
cout << "Y coordinate of the centroid for given cross section, Y_Bar = " << y_bar << " mm" << endl;
for (int i = 1; i <= n; i++) { // Finds moment of inertia
double d = (y[i] - y_bar);
I += (b[i] * pow(h[i], 3.0) / 12.0) + (A[i] * pow(d, 2.0));
}
cout << "Moment of Inertia, I = " << I << " mm^4" << endl;
for (int i = 1; i <= n; i++) { // Calculates first moment of inertia
Q[i] = A[i] * (y[i] - y_bar);
}
for (int i = 1; i <= n - 1; i++) {
if (b[i] <= b[i + 1]) {
t = b[i];
}
else {
t = b[i + 1];
}
Tau[i] = (abs(V * Q[i]) / (I * t));
}
for (int i = 1; i <= n - 1; i++) {
if (i <= 2) {
e += Tau[i];
}
else {
e -= Tau[i];
}
cout << "Shear stress between sections " << i << " and " << i + 1 << " = " << e << " MPa" <<
endl;
}
}
First of all double b[n]; is not a function, it is an array. This error is common with 2-D arrays. However, you aren't using any 2-D arrays here. Also, your code has no error unless you provide specific inputs which cause this error.
You can see the output for some random inputs:
Applied shear force, V = 0.004 kN
Y coordinate of the centroid for given cross section, Y_Bar = 3.29661 mm
Moment of Inertia, I = 322.476 mm^4
Shear stress between sections 1 and 2 = 0.147082 MPa
Shear stress between sections 2 and 3 = 0.231598 MPa
This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}
Everything is working like it's supposed too, except when I output to the text file I can not figure out how to keep all the output lined up. My teacher wouldn't help me and I've literally been doing trial and error with "fixed, setprecision, left, setw(), etc" for a few hours now.
//Project #5
//Start Date: November 17th
//Due Date: November 23rd
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
double f = 3.14159;
double upperBound = 0;
double lowerBound = 0;
double increment = 0;
double tempVal = 0;
double powVal = 0;
double expVal = 0;
double fact = 0;
double sinVal = 0;
double x = 0.0;
char userCont = 'Y';
int n = 0;
int i = 0;
//Factorial function using recursion...
double factorial(const int n) {
if (n <= 1) return 1;
fact = n * factorial(n - 1);
return fact;
}
//Power function using recursion...
double power(const double x, const int n) {
if (n <= 0)
return 1;
powVal = x * power(x, n - 1);
return powVal;
}
//my_sin function using power and factorial functions
double my_sin(const double x) {
sinVal = 0;
for (int k = 0; k < 50; k++) {
sinVal += power(-1, k) * (power(x, 2 * k + 1) / factorial(2 * k + 1));
}
return sinVal;
}
//my_exp(x) Function
double my_exp(const double x) {
expVal = 0;
for (int k = 0; k < 50; k++) {
expVal += power(x, k) / factorial(k);
}
return expVal;
}
int main() {
ofstream fout("output.text");
while (userCont == 'y' || userCont == 'Y') {
cout << "Enter lower and upper bounds: ";
cin >> upperBound >> lowerBound;
cout << "Enter Increment: ";
cin >> increment;
//Checking if upper and lower bounds are in the right order...
if (upperBound < lowerBound) {
tempVal = upperBound;
upperBound = lowerBound;
lowerBound = tempVal;
}
fout << "x sin(x) my_sin(x) e(x) " <<
"my_el(x) my_exp(x)" << endl;
//Loop to display and increase x by the incrememnt
for (x = lowerBound; x <= upperBound; x = x + increment) {
fout.precision(7);
fout << setw(8) << left << x << " ";
fout << setw(8) << my_sin(x) << setw(8) << " ";
fout << setw(8) << sin(x) << setw(8) << " ";
fout << setw(8) << exp(x) << setw(8) << " ";
fout << setw(8) << exp(x) << setw(8) << " ";
fout << my_exp(x) << endl;
}
cout << "Another (y/n)? ";
cin >> userCont;
}
return 0;
}
Here's how it's supposed to look
Some cleanup and the best I could to mimick the formatting, hopefully it is of some inspiration/assistance.
Important Note how I removed all the global variables. They're bad :(
Live On Coliru
// Project #5
// Start Date: November 17th
// Due Date: November 23rd
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
double factorial(const int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
double power(const double x, const int n) {
if (n <= 0)
return 1;
return x * power(x, n - 1);
}
// my_sin function using power and factorial functions
double my_sin(const double x) {
double sinVal = 0;
for (int k = 0; k < 50; k++) {
sinVal += power(-1, k) * (power(x, 2 * k + 1) / factorial(2 * k + 1));
}
return sinVal;
}
// my_exp(x) Function
double my_exp(const double x) {
double expVal = 0;
for (int k = 0; k < 50; k++) {
expVal += power(x, k) / factorial(k);
}
return expVal;
}
int main() {
ofstream fout("output.text");
char userCont = 'Y';
while (userCont == 'y' || userCont == 'Y') {
cout << "Enter lower and upper bounds: ";
double upperBound, lowerBound;
cin >> upperBound >> lowerBound;
cout << "Enter Increment: ";
double increment = 0;
cin >> increment;
// Checking if upper and lower bounds are in the right order...
if (upperBound < lowerBound) {
std::swap(upperBound, lowerBound);
}
fout << " x sin(x) my_sin(x) e(x) my_el(x) my_exp(x)" << endl;
// Loop to display and increase x by the incrememnt
for (double x = lowerBound; x <= upperBound; x = x + increment) {
fout.precision(7);
fout << right << std::fixed << std::setprecision(7) << setw(12) << x << " ";
fout << right << std::fixed << std::setprecision(7) << setw(12) << my_sin(x) << setw(4) << " ";
fout << right << std::fixed << std::setprecision(7) << setw(12) << sin(x) << setw(4) << " ";
fout << right << std::fixed << std::setprecision(7) << setw(12) << exp(x) << setw(4) << " ";
fout << right << std::fixed << std::setprecision(7) << setw(12) << exp(x) << setw(4) << " ";
fout << my_exp(x) << endl;
}
cout << "Another (y/n)? ";
cin >> userCont;
}
}
Output:
x sin(x) my_sin(x) e(x) my_el(x) my_exp(x)
0.0000000 0.0000000 0.0000000 1.0000000 1.0000000 1.0000000
0.1000000 0.0998334 0.0998334 1.1051709 1.1051709 1.1051709
0.2000000 0.1986693 0.1986693 1.2214028 1.2214028 1.2214028
0.3000000 0.2955202 0.2955202 1.3498588 1.3498588 1.3498588
0.4000000 0.3894183 0.3894183 1.4918247 1.4918247 1.4918247
0.5000000 0.4794255 0.4794255 1.6487213 1.6487213 1.6487213
0.6000000 0.5646425 0.5646425 1.8221188 1.8221188 1.8221188
0.7000000 0.6442177 0.6442177 2.0137527 2.0137527 2.0137527
0.8000000 0.7173561 0.7173561 2.2255409 2.2255409 2.2255409
0.9000000 0.7833269 0.7833269 2.4596031 2.4596031 2.4596031
1.0000000 0.8414710 0.8414710 2.7182818 2.7182818 2.7182818
1.1000000 0.8912074 0.8912074 3.0041660 3.0041660 3.0041660
1.2000000 0.9320391 0.9320391 3.3201169 3.3201169 3.3201169
1.3000000 0.9635582 0.9635582 3.6692967 3.6692967 3.6692967
1.4000000 0.9854497 0.9854497 4.0552000 4.0552000 4.0552000
1.5000000 0.9974950 0.9974950 4.4816891 4.4816891 4.4816891
1.6000000 0.9995736 0.9995736 4.9530324 4.9530324 4.9530324
1.7000000 0.9916648 0.9916648 5.4739474 5.4739474 5.4739474
1.8000000 0.9738476 0.9738476 6.0496475 6.0496475 6.0496475
1.9000000 0.9463001 0.9463001 6.6858944 6.6858944 6.6858944
2.0000000 0.9092974 0.9092974 7.3890561 7.3890561 7.3890561
2.1000000 0.8632094 0.8632094 8.1661699 8.1661699 8.1661699
2.2000000 0.8084964 0.8084964 9.0250135 9.0250135 9.0250135
2.3000000 0.7457052 0.7457052 9.9741825 9.9741825 9.9741825
2.4000000 0.6754632 0.6754632 11.0231764 11.0231764 11.0231764
2.5000000 0.5984721 0.5984721 12.1824940 12.1824940 12.1824940
2.6000000 0.5155014 0.5155014 13.4637380 13.4637380 13.4637380
2.7000000 0.4273799 0.4273799 14.8797317 14.8797317 14.8797317
2.8000000 0.3349882 0.3349882 16.4446468 16.4446468 16.4446468
2.9000000 0.2392493 0.2392493 18.1741454 18.1741454 18.1741454
3.0000000 0.1411200 0.1411200 20.0855369 20.0855369 20.0855369
3.1000000 0.0415807 0.0415807 22.1979513 22.1979513 22.1979513
3.2000000 -0.0583741 -0.0583741 24.5325302 24.5325302 24.5325302
3.3000000 -0.1577457 -0.1577457 27.1126389 27.1126389 27.1126389
3.4000000 -0.2555411 -0.2555411 29.9641000 29.9641000 29.9641000
3.5000000 -0.3507832 -0.3507832 33.1154520 33.1154520 33.1154520
3.6000000 -0.4425204 -0.4425204 36.5982344 36.5982344 36.5982344
3.7000000 -0.5298361 -0.5298361 40.4473044 40.4473044 40.4473044
3.8000000 -0.6118579 -0.6118579 44.7011845 44.7011845 44.7011845
3.9000000 -0.6877662 -0.6877662 49.4024491 49.4024491 49.4024491
4.0000000 -0.7568025 -0.7568025 54.5981500 54.5981500 54.5981500
4.1000000 -0.8182771 -0.8182771 60.3402876 60.3402876 60.3402876
4.2000000 -0.8715758 -0.8715758 66.6863310 66.6863310 66.6863310
4.3000000 -0.9161659 -0.9161659 73.6997937 73.6997937 73.6997937
4.4000000 -0.9516021 -0.9516021 81.4508687 81.4508687 81.4508687
4.5000000 -0.9775301 -0.9775301 90.0171313 90.0171313 90.0171313
4.6000000 -0.9936910 -0.9936910 99.4843156 99.4843156 99.4843156
4.7000000 -0.9999233 -0.9999233 109.9471725 109.9471725 109.9471725
4.8000000 -0.9961646 -0.9961646 121.5104175 121.5104175 121.5104175
4.9000000 -0.9824526 -0.9824526 134.2897797 134.2897797 134.2897797
5.0000000 -0.9589243 -0.9589243 148.4131591 148.4131591 148.4131591
5.1000000 -0.9258147 -0.9258147 164.0219073 164.0219073 164.0219073
5.2000000 -0.8834547 -0.8834547 181.2722419 181.2722419 181.2722419
5.3000000 -0.8322674 -0.8322674 200.3368100 200.3368100 200.3368100
5.4000000 -0.7727645 -0.7727645 221.4064162 221.4064162 221.4064162
5.5000000 -0.7055403 -0.7055403 244.6919323 244.6919323 244.6919323
5.6000000 -0.6312666 -0.6312666 270.4264074 270.4264074 270.4264074
5.7000000 -0.5506855 -0.5506855 298.8674010 298.8674010 298.8674010
5.8000000 -0.4646022 -0.4646022 330.2995599 330.2995599 330.2995599
5.9000000 -0.3738767 -0.3738767 365.0374679 365.0374679 365.0374679
6.0000000 -0.2794155 -0.2794155 403.4287935 403.4287935 403.4287935
6.1000000 -0.1821625 -0.1821625 445.8577701 445.8577701 445.8577701
6.2000000 -0.0830894 -0.0830894 492.7490411 492.7490411 492.7490411
6.3000000 0.0168139 0.0168139 544.5719101 544.5719101 544.5719101
6.4000000 0.1165492 0.1165492 601.8450379 601.8450379 601.8450379
6.5000000 0.2151200 0.2151200 665.1416330 665.1416330 665.1416330
6.6000000 0.3115414 0.3115414 735.0951892 735.0951892 735.0951892
6.7000000 0.4048499 0.4048499 812.4058252 812.4058252 812.4058252
6.8000000 0.4941134 0.4941134 897.8472917 897.8472917 897.8472917
6.9000000 0.5784398 0.5784398 992.2747156 992.2747156 992.2747156
7.0000000 0.6569866 0.6569866 1096.6331584 1096.6331584 1096.6331584
7.1000000 0.7289690 0.7289690 1211.9670745 1211.9670745 1211.9670745
7.2000000 0.7936679 0.7936679 1339.4307644 1339.4307644 1339.4307644
7.3000000 0.8504366 0.8504366 1480.2999276 1480.2999276 1480.2999276
7.4000000 0.8987081 0.8987081 1635.9844300 1635.9844300 1635.9844300
7.5000000 0.9380000 0.9380000 1808.0424145 1808.0424145 1808.0424145
7.6000000 0.9679197 0.9679197 1998.1958951 1998.1958951 1998.1958951
7.7000000 0.9881682 0.9881682 2208.3479919 2208.3479919 2208.3479919
7.8000000 0.9985433 0.9985433 2440.6019776 2440.6019776 2440.6019776
7.9000000 0.9989413 0.9989413 2697.2823283 2697.2823283 2697.2823283
8.0000000 0.9893582 0.9893582 2980.9579870 2980.9579870 2980.9579870
8.1000000 0.9698898 0.9698898 3294.4680753 3294.4680753 3294.4680753
8.2000000 0.9407306 0.9407306 3640.9503073 3640.9503073 3640.9503073
8.3000000 0.9021718 0.9021718 4023.8723938 4023.8723938 4023.8723938
8.4000000 0.8545989 0.8545989 4447.0667477 4447.0667477 4447.0667477
8.5000000 0.7984871 0.7984871 4914.7688403 4914.7688403 4914.7688403
8.6000000 0.7343971 0.7343971 5431.6595914 5431.6595914 5431.6595914
8.7000000 0.6629692 0.6629692 6002.9122173 6002.9122173 6002.9122173
8.8000000 0.5849172 0.5849172 6634.2440063 6634.2440063 6634.2440063
8.9000000 0.5010209 0.5010209 7331.9735392 7331.9735392 7331.9735392
9.0000000 0.4121185 0.4121185 8103.0839276 8103.0839276 8103.0839276
9.1000000 0.3190984 0.3190984 8955.2927035 8955.2927035 8955.2927035
9.2000000 0.2228899 0.2228899 9897.1290587 9897.1290587 9897.1290587
9.3000000 0.1244544 0.1244544 10938.0192082 10938.0192082 10938.0192082
9.4000000 0.0247754 0.0247754 12088.3807302 12088.3807302 12088.3807302
9.5000000 -0.0751511 -0.0751511 13359.7268297 13359.7268297 13359.7268297
9.6000000 -0.1743268 -0.1743268 14764.7815656 14764.7815656 14764.7815656
9.7000000 -0.2717606 -0.2717606 16317.6071980 16317.6071980 16317.6071980
9.8000000 -0.3664791 -0.3664791 18033.7449278 18033.7449278 18033.7449278
9.9000000 -0.4575359 -0.4575359 19930.3704382 19930.3704382 19930.3704382
10.0000000 -0.5440211 -0.5440211 22026.4657948 22026.4657948 22026.4657948
I am writing a program that will utilize Lagrange Standard Form in a Piecewise Linear fashion to interpolate a polynomial of degree n. I have the code working properly for the first subinterval and the third and fourth subintervals, but, for some reason that I cannot figure, I am receiving NaN as the output for my second subinterval. The second subinterval is calculated beneath the line commented //P2. I have racked my brain and tried every alteration I could think of to fix the problem, but have had no luck. If anyone could provide some insight I would be greatly appreciative. Note that I only included code up to the second interpolating polynomial as the third and fourth follow in similar fashion. I apologize in advance for the brutality of my code. I am relatively new to C++ and have not had time to acquire the elegance that would probably be expected for a problem of this magnitude. Thanks again.
ofstream Outfile;
Outfile.open ("PiecewiseLagrange_D.dat");
double *P1 = new double[201]; //Polynomial 1
double *P2 = new double[201]; //Polynomial 2
double *P3 = new double[201]; //Polynomial 3
double *P4 = new double[201]; //Polynomial 4
double *x = new double[201]; //Interpolating points/x's
double *x1 = new double[(int)n+1]; //First subinterval/mesh/xi's
double *x2 = new double[(int)n+1]; //Second subinterval
double *x3 = new double[(int)n+1]; //Third subinterval
double *x4 = new double[(int)n+1]; //Fourth subinterval
double a, b; //interval end points
char func; //function selection
double xDifference1;
double xDifference2;
cout << "Enter an interval with integer end points (lesser value first)";
cin >> a >> b;
for (int i=0; i<=n; i++) //Initialize
{
P1[i] = 0;
P2[i] = 0;
P3[i] = 0;
P4[i] = 0;
x[i] = 0;
x1[i] = 0;
x2[i] = 0;
x3[i] = 0;
x4[i] = 0;
}
x1[0] = a;
for (int i=0; i<=n; i++)
{
x1[i] = x1[0] + i*(((b-a)/4)/n);
cout << x1[i] << endl;
}
cout << endl;
x2[0] = x1[(int) n];
for (int i=0; i<=n; i++)
{
x2[i] = x2[0] + i*(((b-a)/4)/n);
cout << x2[i] << endl;
}
cout << endl;
x3[0] = x2[(int) n];
for (int i=0; i<=n; i++)
{
x3[i] = x3[0] + i*(((b-a)/4)/n);
cout << x3[i] << endl;
}
cout << endl;
x4[0] = x3[(int) n];
for (int i=0; i<=n; i++)
{
x4[i] = x4[0] + i*(((b-a)/4)/n);
cout << x4[i] << endl;
}
cout << "Enter a function to evaluate (1,2, or 3):";
cin >> func;
//cout << "Polynomial is g1(x) on [" << a << "," << b << "]" << endl;
if (func == '1')
{
//P1
x[0] = a;
for (int i=0; i<=200; i++)
{
x[i] = x[0] + i*((x1[(int) n] - x1[0])/200);
}
for (int j=0; j<=200; j++)
{
xDifference1 = 0;
xDifference2 = 0;
for (int i=0; i<=n; i++)
{
xDifference1 = (x1[i] - x1[i+1]);
xDifference2 = (x1[i+1] - x1[i]);
P1[j] = F1(x1[i])*((x[j] - x1[i+1])/xDifference1) + F1(x1[i+1])*((x[j] - x1[i])/xDifference2);
}
Outfile << x[j] << " " << P1[j] << " " << F1(x[j]) << endl;
cout << setw(8) << x[j] << setw(12) << P1[j] << endl;
}
cout << endl;
//P2
x[0] = x1[(int) n];
for (int i=0; i<=200; i++)
{
x[i] = x[0] + i*((x2[(int) n] - x2[0])/200);
}
for (int j=0; j<=200; j++)
{
xDifference1 = 0;
xDifference2 = 0;
for (int i=0; i<=n; i++)
{
xDifference1 = (x2[i] - x2[i+1]);
xDifference2 = (x2[i+1] - x2[i]);
P2[j] = F1(x2[i])*((x[j] - x2[i+1])/xDifference1) + F1(x2[i+1])*((x[j] - x2[i])/xDifference2);
}
Outfile << x[j] << " " << P2[j] << " " << F1(x[j]) << endl;
cout << setw(8) << x[j] << setw(12) << P2[j] << " " << F1(x[j]) << endl;
}
cout << endl;
Since you're not calling any other functions, you'll get a NaN when you divide zero by zero (0.0 / 0.0). At some point your xDifference1 and/or xDifference2 are zero.
Dividing a non-zero by zero gives an infinity.
Edit However, as that's apparently not the case further investigation shows that the various x arrays, including x2, have n+1 elements in them, indexed 0 thru n. During your loop, you access x2[i+1]. Since i will equal n on the last iteration, you access element x2[n+1] which is out of bounds of the array and results in undefined behavior. In this case, the random memory right after the array generates a NaN for x2 but not the other arrays.
In an unrelated note, you your inner i loops you assign to P2[j] for every iteration, so the only value you get out of the loops is from the last iteration. Did you mean to use P2[j] += ...?