C++ truncation error? - c++

I am learning C++ and came upon this problem while trying to use a formula to calculate the current.
And I got: 0.628818 where the answer should be:
f=200 Hz
R=15 Ohms
C=0.0001 (100µF)
L=0.01476 (14.76mH)
E = 15 V
Answer: I = 0.816918A (calculated)
Below is my code:
#include <iostream>
#include <cmath>
int main()
{
const double PI = 3.14159;
double r = 15;
double f = 200;
double c = 0.0001;
double l = 0.01476;
double e = 15;
double ans = e / std::sqrt(std::pow(r, 2) + (std::pow(2 * PI*f*l - (1.0 / 2.0 * PI*f*c), 2)));
std::cout << "I = " << ans << "A" << std::endl;
}
I have read about truncation errors and tried to use 1.0/2.0 but doesn't seem to work either.

Truncation error refers to using only the first N terms of an infinite series to estimate a value. So the answer to your question is "No." You might find the following to be of some interest however....
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
template<typename T>
T fsqr(T x) { return x * x; }
// Numerically stable and non-blowuppy way to calculate
// sqrt(a*a+b*b)
template<typename T>
T pythag(T a, T b) {
T absA = fabs(a);
T absB = fabs(b);
if (absA > absB)
{
return absA*sqrt(1.0 + fsqr(absB / absA));
} else if (0 == absB) {
return 0;
} else {
return absB*sqrt(1.0 + fsqr(absA / absB));
}
}
int main () {
double e, r, f, l, c, ans;
const double PI = 3.14159265358972384626433832795028841971693993751058209749445923078164062862089986280348253421170;
cout << "Insert value for resistance: " << endl;
cin >> r ;
cout << "Insert value for frequency: " << endl;
cin >> f;
cout << "Insert value for capacitance: " << endl;
cin >> c;
cout << "Insert value for inductance: " << endl;
cin >> l;
cout << "Insert value for electromotive force (voltage): " << endl;
cin >> e;
ans = e / pythag(r, 2*PI*f*l - (1/(2*PI*f*c)) );
cout << "I = " << ans << "A" << endl;
system("pause");
return 0;
}
Just kidding about all that PI.

The main problem is multiplying ½ by πfC instead of dividing, here:
(1.0 / 2.0 * PI*f*c)
This sort of problem is best avoided by using suitable named values (that also allows you to use faster and more precise x*x instead of std::pow(x,2)).
You can also remove some of that arithmetic by using the standard hypotenuse function instead of squaring and sqrting inline:
double ans = e / std::hypot(r, (2*PI*f*l - 0.5/PI/f/c));
#include <iostream>
#include <cmath>
int main()
{
static constexpr double PI = 4 * std::atan(1);
double r = 15; // ohm
double f = 200; // hertz
double c = 0.0001; // farad
double l = 0.01476; // henry
double e = 15; // volt
double current = e / std::hypot(r, (2 * PI*f*l - 0.5/PI/f/c));
std::cout << "I = " << current << "A" << std::endl;
}

Related

Quadratic equation solver outputting in unknown format

I'm trying to make a quadratic equation solver, but for some reason my program is giving me answers in an unknown format.
I entered the simple quadratic equation x^2 + 2x + 1 = 0, expecting my program to give x = -1 or x = -1, but instead it gave x = 0138151E or x = 0138152D. It looks like it outputs these values for x for any inputs (not recognizing unreal answers and catching them). Why is this and how can I fix it?
#include "../std_lib_facilities_revised.h"
class Imaginary {};
double square(int a)
{
return a * a;
}
double quadratic_solver_pos(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b + sqrt(radicand)) / (2 * a);
return x;
}
double quadratic_solver_neg(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b - sqrt(radicand)) / (2 * a);
return x;
}
int main()
try {
cout << "This program is a quadratic equation solver.\n";
cout << "Quadratic equations are of the form: ax^2 + bx + c = 0\n";
cout << "Enter a, b, and c, respectively:\n";
double a = 0;
double b = 0;
double c = 0;
cin >> a >> b >> c;
cout << "Your quadratic equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n";
cout << "x = " << quadratic_solver_pos << " or x = " << quadratic_solver_neg << '\n';
}
catch (Imaginary) {
cout << "x is unreal\n";
}
You don't pass your variables to your functions.
You need to do it like so quadratic_solver_pos(a, b, c);.

C++ Int returns different value than double for same input in Atom [duplicate]

This question already has answers here:
How does the function pow work?
(2 answers)
Closed 4 years ago.
I'm doing algorithm for solving Quadratic equation.
I type for A = 4, B = 10, C = 4 which gives value of 36 for delta.
My issue is that
int delta;
returns value of 35, and
double delta;
returns value of 36.
I'm using Atom text editor, rest of code is below.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b,c;
int delta;
int x1, x2;
cout << "Rownanie kwadratowe w postaci ax^2 + bx + c = 0" << endl;
cout << "Podaj wartosc A" << endl;
cin >> a;
cout << "Podaj wartosc B" << endl;
cin >> b;
cout << "Podaj wartosc C" << endl;
cin >> c;
delta = pow(b,2) - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}
It works for me. Bellow code is much shorter and better for the Minimum example, isn't it?
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a = 4, b = 10, c = 4;
int delta = pow(b,2) - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}
If you use integral arithmetic then use integral not floating point operations. The problem consists of floats. Result of pow(b, 2) may be like 99.99999999997, that rounded down to int is 99.
#include <iostream>
using namespace std;
int main()
{
int a = 4, b = 10, c = 4;
int delta = b * b - (4 * a * c);
cout << "Delta = " << delta << endl;
return 0;
}

Round very small numbers to zero (c++)

Is there any command in C++ to make,
1.354322e-23
into
0
This is my (simple) Program
#include "stdafx.h"
#include <iostream>
#include<iomanip>
int main()
{
float x;
std::cin >> x;
std::cout << x << std::endl;
return 0;
}
When I type values like,
2.2356e-17
It gives,
2.2356e-017
std::setprecision won't work either...
Edit:
OK this is my problem.
I created a program that can give sin cos and and tan values.
For cos 90, I want it to be 0 instead of -4.311e-008
Heres my real program
#include "stdafx.h"
#include <iostream>
#include<iomanip>
float Pi()
{
float pi = (atan(1) * 4);
return pi;
}
int Selector()
{
using namespace std;
cout << "Type:\t1 for Degrees\n\t2 for Radians\n\t3 for Gradians\n\nYour Choice : ";
int x;
cin >> x;
return x;
}
float D_R(float a)
{
float q = (a / 180);
float r = q*Pi();
return r;
}
float G_R(float a)
{
float q = (a / 200);
float r = q*Pi();
return r;
}
float All(float a, float o)
{
using namespace std;
std::cout << setprecision(5) << "sin(" << o << ") = " << sin(a) << std::endl;
std::cout << setprecision(5) << "cos(" << o << ") = " << cos(a) << std::endl;
std::cout << setprecision(5) << "tan(" << o << ") = " << tan(a) << std::endl;
return 0;
}
int main()
{
using namespace std;
int x = Selector();
cout << "Enter your angle : ";
float o;
cin >> o;
float d = D_R(o);
float g = G_R(o);
if (x == 1)
All(d, o);
else if (x == 2)
All(o, o);
else if (x == 3)
All(g, o);
return 0;
}
Edit:
Ok I came up with inserting
if (std::abs(sin(a)) < 0.0001) a = 0;
if (std::abs(cos(a)) < 0.0001) a = 0;
if (std::abs(tan(a)) < 0.0001) a = 0;
before my All() function
And that solved my problem
C++ can't arbitrarily round numbers down to 0 for you, it's up to you to define what a "very small number" is for your purposes.
Once you've determined the threshold, you simply need
if (std::abs(number) < THRESHOLD) number = 0;
RE: Your edits
For cos 90, I want it to be 0 instead of -4.311e-008
Again, it's up to you to define what the threshold is. Do you want 0.00000001 to be rounded to 0? What about 0.0001? What about 0.1? You need to define the line where rounding occurs.
Probably trunc() does what you want.
#include <cmath>
cout << roundf(2.2356e-17) << " " << trunc(2.2356e-17) << endl;
Output
0 0
See Also: round(), trunc(), nearbyint().

Value Representation Issue

The input for a,b,c are 25,27.5,40.
The correct answer that should be displayed is 754573.2, but I continue getting 754573.17 despite reading about how to solve this. I also am not allowed to use setprecision() to solve the issue.
What am I doing wrong?
#include <iostream>
using namespace std;
int main() {
double a, b, c;
double g;
double v;
double ci = 123.00;
double i = 15;
cout << "enter the 3 values: ";
cin >> a >> b >> c;
a = a * i;
b = b * i;
c = c * i;
v = a * b * c;
g = static_cast<int>(v / ci * 100 + .5) / 100.0;
cout << "The answer is " << g;
return 0;
}
Thanks everyone! I got it to work.
cout is using a default precision, and that is why the output is rounded to 5 digits.
To see that, call cout::precision();
A cheesy answer to try is using sprintf:
char *result = char[256];
sprintf(&result, "%.2lf", g);
cout << result;
int g = static_cast<int>(v / ci);
int h = static_cast<int>((100 * v / ci) + 0.5);
int i = h - g * 100;
cout << "The answer is " << g << "." << i << "\n";

Calculating mathematical constant e using while loop

I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
e += (1/number);
x++;
}
cout << endl << "The mathematical constantr e is: "
<< setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
However, when I tried e^x the following code returned a completely wrong value:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
exponent = temp;
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
int counterr = 1;
while (counterr < x)
{
exponent *= exponent;
counterr++;
}
e += (exponent/number);
x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
Any ideas where the calculations went wrong?
This line:
exponent *= exponent;
is wrong. It should be:
exponent *= temp;