Round very small numbers to zero (c++) - 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().

Related

My function factoring program has problems with variables, shows incorrect answers

I'm making a program that factors functions (f(x), not fully factored though):
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int x3;
int x2;
int x;
int remain;
int r = 0;
int factor;
int main() {
int b, i, j = 0;
int factors[101];
cout << "f(x) = x^3 + x^2 + x + r (Factor tool)" << endl;
cout << "x^3?: ";
cin >> x3;
cout << "x^2: ";
cin >> x2;
cout << "x: ";
cin >> x;
printf("remain (Y intercept): ");
scanf("%d", &b);
cout << "f(x) = " << x3 << "x^3 + " << x2 << "x^2 + " << x << "x + " << b
<< "" << endl;
cout << "factors of remainder are: " << endl;
for (i = 1; i <= b; i++) {
if (b % i == 0) {
factors[j++] = i;
printf("%d\t", i);
}
}
getchar();
while (true) {
int good;
if (factors[1] == 0) {
cout <<endl;
cout << "Equation Cannot be factored";
break;
}
int factorv = factors[r];
int nx1 = x3 * factors[r];
int nx2 = (nx1 + x2);
int nx3 = x + (nx2 * factors[r]);
int nx4 = remain + (nx3 * factors[r]);
if (nx4 == 0) {
int factored = (0 - factors[r]);
cout <<endl;
cout << "The Factored Function: f(x) = "
<< "(x " << factored << ")(" << nx1 << "x^3 + " << nx2 << "x^2 + "
<< nx3 << "x"
<< ")"
<< "";
break;
} else {
r = r + 1;
}
}
}
but in this part of the code, it shows as (x 0)(0x^3 + (x3 input instead of calculated nx1)x^2 + (x2 input instead of calculated nx2)x).
if (nx4 == 0) {
int factored = (0-factors[r]);
cout<<"The Factored Function: f(x) = "<<"(x "<<factored<<")("<<nx1<<"x^3 + "<<nx2<<"x^2 + "<<nx3<<"x"<<")"<<"";
break;
What happen to my nx variables? Why is it coming up incorrect or as a 0 when it was calculated properly above?
You have some of your variables twice:
int nx1;
int nx2;
int nx3;
int nx4;
They exists as global variables and again in the scope of main. They have the same name but are different variables.
Take the lesson: Global variables are no good.
Moreover you have a logic error in your code. When I add a std::cout << r << std::endl; in the last while loop I see its value increasing until there is a segfault, because factors[r] is out-of-bounds. broken code # wandbox
I cannot really tell you how to fix it, because I would have to dive into the maths first. I can only suggest you to never use infinte loops in numerical codes without an "emergency exit". What i mean is that unless fully tested, you cannot be sure that the loop will end at some point and when it doesn't typically the consequences are bad and difficult to diagnose. Always make sure the loop will end at some point:
int max_iteratons = 100;
int counter;
while (counter < max_iteratons) {
// do something
++counter;
}
if (counter == max_iterations) std::cout << "i have a bug :(";

Fractions instead of decimals

So, I am Writing this little program in c++, it's made to compute various values with lines (sorry i am french, i don't know how to say it in English, but they are the lines with equation types Y = kx + t).
And I want my program to output fractions instead of decimals (2/3 instead of 0.666666666...).
Can anyone tell me how ?
I read online that there are some libraries for that purpose, can anyone help me on how to use them and/or how to implement them in my code ?
Thanks :)
#include "pch.h"
#include <iostream>
#include <string>
std::string mainAnswer;
bool endVar = false;
void lineEquationFromTwoPoints() {
mainAnswer.clear();
double Xa = 0;
double Ya = 0;
double Xb = 0;
double Yb = 0;
double Y = 0;
double X = 0;
double k = 0;
double t = 0;
std::cout << ("Enter the Coordinates of your first point in this format x y : ");
std::cin >> Xa >> Ya;
std::cout << ("Enter the Coordinates of your second point in this format x y : ");
std::cin >> Xb >> Yb;
if (Xb != Xa && Yb != Ya) {
k = (Yb - Ya) / (Xb - Xa);
t = -(Xa)*k + Ya;
if (k != 1 && t != 0) {
std::cout << ("Y = ") << k << ("x + ") << t << std::endl;
}
else if (k == 1) {
std::cout << ("Y = ") << ("x") << ("+") << t << std::endl;
}
else if (t == 0) {
std::cout << ("Y = ") << k << ("x") << std::endl;
}
}
else if (Xb == Xa) {
std::cout << ("Coordinates of the first point are Equal");
}
else if (Yb == Ya) {
std::cout << ("Coordinates of the second point are Equal");
}
else if (Xb == Xa && Yb == Ya) {
std::cout << ("Coordinates of both points are Equal");
}
}
void triangle() {
double Xa = 0;
double Ya = 0;
double Xb = 0;
double Yb = 0;
double Xc = 0;
double Yc = 0;
double Ym1 = 0;
double Xm1 = 0;
double km1 = 0;
double tm1 = 0;
double Ym2 = 0;
double Xm2 = 0;
double km2 = 0;
double tm2 = 0;
double Ym3 = 0;
double Xm3 = 0;
double km3 = 0;
double tm3 = 0;
std::cout << ("Work in progress. . . :-)") << std::endl;
}
void Choose() {
while (endVar != true) {
std::cout << ("Lines:") << std::endl;
std::cout << ("------") << std::endl << std::endl;
std::cout << ("Choose What Line Operations do You Want Me To Perform:") << std::endl;
std::cout << ("1.Formulas") << std::endl;
std::cout << ("2.Calculation of a Line's equation from 2 points") << std::endl;
std::cout << ("3.Calculation of all data in a triangle") << std::endl;
std::cout << ("Type Exit to Exit") << std::endl << std::endl;
std::getline(std::cin, mainAnswer);
if (mainAnswer == "exit" || mainAnswer == "Exit") {
std::exit;
endVar = true;
}
else if (mainAnswer == "1") {
std::cout << ("Formulas will be added Here once main program with main calculation functions will be finished") << std::endl;
}
else if (mainAnswer == "2") {
lineEquationFromTwoPoints();
}
else if (mainAnswer == "3") {
triangle();
}
else {
std::cout << ("Unexpected error occured. Please relaunch program.");
std::exit;
}
}
}
int main()
{
Choose();
return 0;
}
A nice way to approximate a float with a fraction is to used continued fractions. In the following code, epsis the desired precision. xis assumed to be strictly positive.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <tuple>
#include <vector>
#include <cmath>
// Continued fraction
std::pair<int, int> fract_cont (double x, double eps = 1.0e-3) {
std::vector<int> a;
std::vector<int> b;
a.push_back(1);
b.push_back(0);
int q = int(x);
a.push_back(q);
b.push_back(1);
double err = x - q;
double e = (x != q) ? 1.0 / (x - q) : 0.0;
int i = 1;
while (std::abs(err) > eps) {
i++;
q = int (e);
e = 1.0 / (e - q);
a.push_back (q * a[i-1] + a [i-2]);
b.push_back (q * b[i - 1] + b[i-2]);
err = x - double (a[i]) / b[i];
}
return std::make_pair(a[i], b[i]);
}
int main() {
int a, b;
double x = 4 * atan(1.0);
std::tie (a,b) = fract_cont(x);
std::cout <<"Pi = " << std::setprecision(9) << x << " ~= " << a << "/" << b << "\n";
return 0;
}
Detailed information on continued fractions is available on Wikipedia for example.
If you don't need a high precision or if you assume that the denominators will be small, you can use a brute force approach instead, simply incrementing the denominator b.

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;
}

C++ truncation error?

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;
}

C++ Walkthrough cout.setf(ios::fixed); and cout.precision();

/* Problem 38 */
#include <iostream>
using namespace std;
class abc {
double n;
public:
abc() { n = 67.5; cout << "1\n"; }
abc(double num) { set(num); cout << "2\n"; }
double get() const { cout<<"3\n"; return n; }
virtual void set(double num) {
if (num < 10)
n = 10;
else if (num > 100)
n = 100;
else
n = num;
cout << "4\n";
}
};
class def: public abc {
double m;
public:
def() { m = 6.2; cout << "5\n"; }
def(double num1, double num2): abc(num1) {
set(num2 - abc::get()); cout << "6\n"; }
double get() const {
cout << "7\n"; return m + abc::get(); }
void set(double num) {
if (num < 10 || 100 < num)
m = num;
else
m = 55;
cout << "8\n";
}
};
void do_it(abc &var, double num)
{ cout << var.get() << '\n';
var.set(num);
cout << var.get() << '\n';
}
int main()
{ abc x(45);
def y(2, 340);
cout.setf(ios::fixed);
cout.precision(3);
do_it(x, 200);
do_it(y, 253);
cout << x.get() << '\n';
cout << y.get() << '\n';
return 0;
}
With the above code I just wanted to know what below two lines will really do in the above code
cout.setf(ios::fixed);
cout.precision(3);
Please do not just give me answer some explanation would be so appreciated because I'm doing a walkthrough to prepare for my final exam tomorrow.
I searched and some source says it is to set flags but really I don't get what is the concept of it and how it works
cout.setf(ios::fixed)
makes cout print floats with a fixed number of decimals and
cout.precision(3)
sets this number to be three.
For example, if you got a
double f = 2.5;
then
cout << f;
will print
2.500
Great documentation about how to format your output : Output formatting
It's always usefull when you're trying to do a command-line UI.
#include<iostream>
using namespace std;
int main(){
float large = 2000000000;
cout << large;
return 0;
}
The output will be in scientific notation as:
2e+009
In order to get the value as it is you should use cout.setf(ios::fixed)
#include<iostream>
using namespace std;
int main(){
cout.setf(ios::fixed);
float large = 2000000000;
cout << large;
return 0;
}
The output will be as it is with default precision which is 6 for float.
2000000000.000000
You can set the precision in the above code as:
cout.precision(7);
.....
It's similar to including the manipulation library:
include :
<iomanip>
And then using the following functions
cout << fixed << showpoint;
cout << setprecision(3);