A cancellation error occurs when you are manipulating a very large number with a
ID: 3566091 • Letter: A
Question
A cancellation error occurs when you are manipulating a very large number with a very small number. The large number may cancel out the smaller number. For example, the result of 100000000. 0 + 0. 000000001 is equal to 100000000. 0. To avoid cancellation errors and obtain more accurate results, carefully select the order of computation. For example, in computing the following series, you will obtain more accurate results by computing from right to left rather than from left to right: Write a program that compares the results of the summation series, computing from left to right and from right to left with n = 50000.Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
long double ltor=0; // long double for 16 bytes
for(int i=1;i<=50000;i++) // from left to right
{
ltor+=1/i; //adding 1/i to ltor
}
cout<<"from left to right: "<<ltor; // printing the value after processing from left to right
long double rtol=0; // from right to left
for(int i=50000;i>=1;i--) // running loop from backwards ie; from 50000
{
rtol+=1/i; // adding 1/i to the rtol
}
cout<<"from right to left: "<<rtol; // printing the value after processing from right to left
return 0; // returning zero to main function
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.