I want to use a cubic function but I am getting incorrect values when compared to desmos.
I am currently using pow(), but have tried simply multiplying these numbers by themselves but got the same results.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int distance = 1500;
double aX = (4.8264*pow(10,-8))*distance;
double bX = 0.000364*distance;
double cX = -0.8495*distance;
double rate = -pow(aX,3.0) + pow(bX,2.0) + cX + 592.628;
cout << rate << endl;
return 0;
}
I'm expecting rate to equal values ranging between -40 and 25, but I'm getting values starting at -681 and decreasing from there (I'm testing int distance at 1500 to 3300). Here is the desmos graph that I am using for the function and expected results: https://www.desmos.com/calculator/g9sdww9c9v.
Sorry about this post lol. Looks like I just needed to review what coefficients are because I was cubing and squaring those. All working now
Related
I have a code that tries to solve an integral of a function in a given interval numerically, using the method of Trapezoidal Rule (see the formula in Trapezoid method ), now, for the function sin(x) in the interval [-pi/2.0,pi/2.0], the integral is waited to be zero.
In this case, I take the number of partitions 'n' equal to 4. The problem is that when I have pi with 20 decimal places it is zero, with 14 decimal places it is 8.72e^(-17), then with 11 decimal places, it is zero, with 8 decimal places it is 8.72e^(-17), with 3 decimal places it is zero. I mean, the integral is zero or a number near zero for different approximations of pi, but it doesn't have a clear trend.
I would appreciate your help in understanding why this happens. (I did run it in Dev-C++).
#include <iostream>
#include <math.h>
using namespace std;
#define pi 3.14159265358979323846
//Pi: 3.14159265358979323846
double func(double x){
return sin(x);
}
int main() {
double x0 = -pi/2.0, xf = pi/2.0;
int n = 4;
double delta_x = (xf-x0)/(n*1.0);
double sum = (func(x0)+func(xf))/2.0;
double integral;
for (int k = 1; k<n; k++){
// cout<<"func: "<<func(x0+(k*delta_x))<<" "<<"last sum: "<<sum<<endl;
sum = sum + func(x0+(k*delta_x));
// cout<<"func + last sum= "<<sum<<endl;
}
integral = delta_x*sum;
cout<<"The value for the integral is: "<<integral<<endl;
return 0;
}
OP is integrating y=sin(x) from -a to +a. The various tests use different values of a, all near pi/2.
The approach uses a linear summation of values near -1.0, down to 0 and then up to near 1.0.
This summation is sensitive to calculation error with the last terms as the final math sum is expected to be 0.0. Since the start/end a varies, the error varies.
A more stable result would be had adding the extreme f = sin(f(k)) values first. e.g. sum += sin(f(k=1)), then sum += sin(f(k=3)), then sum += sin(f(k=2)) rather than k=1,2,3. In particular the formation of term x=f(k=3) is likely a bit off from the negative of its x=f(k=1) earlier term, further compounding the issue.
Welcome to the world or numerical analysis.
Problem exists if code used all float or all long double, just different degrees.
Problem is not due to using an inexact value of pi (Exact value is impossible with FP as pi is irrational and all finite FP are rational).
Much is due to the formation of x. Could try the below to form the x symmetrically about 0.0. Compare exactly x generated this way to x the original way.
x = (x0-x1)/2 + ((k - n/2)*delta_x)
Print out the exact values computed for deeper understanding.
printf("x:%a y:%a\n", x0+(k*delta_x), func(x0+(k*delta_x)));
I'm trying to compute a discount factor given a rate and the number of payments to be made per year.
#include <iostream>
using namespace std;
int main()
{
uint32_t due_dates_per_year = 2;
double t = 1;
double rate = 0.05;
double df = pow(1 + rate / due_dates_per_year, -due_dates_per_year * t);
cout << df;
return 0;
}
The output is "inf" but it should be a little less than 1.
Does anyone know what's going on?
The problem is in the exponent (i.e. the second parameter) of std::pow. The expression
-due_dates_per_year * t
is grouped as (-due_dates_per_year) * t (that's how the C++ grammar parses the expression). The unary negation of the unsigned type produces a large (and also unsigned) number which explains the result.
Other than using a signed type for due_dates_per_year, the rearrangement
double df = std::pow(1 + rate / due_dates_per_year, -t * due_dates_per_year);
is a fix.
The program gets 4 points(their coords) that form a convex figure and should give me the angle A2+angle A4 - 180 degrees. For the example :
1 3
0 2
1 1
2 2
I get uA2=90 and uA4=90, but when I do uA2+uA4-180 I get 2.0568e-007, instead of 0. But when I do just uA2+uA4 I get 180. I am sorry if a similar question was asked, but I didn't know how to search for it. Can anyone tell me why it happens and how can I repair it to show the right answer? Tho code:
#include <iostream>
#include <fstream>
#include <cmath>
#define PI 3.14159265
using namespace std;
ifstream f("date.in");
struct punct
{
double x,y;
}A1,A2,A3,A4;
int main()
{
double uA2,uA4;
f>>A1.x>>A1.y>>A2.x>>A2.y>>A3.x>>A3.y>>A4.x>>A4.y;
//calculate cos of both angles
uA2=((A1.x-A2.x)*(A3.x-A2.x)+(A1.y-A2.y)*(A3.y-A2.y))/
(sqrt((A1.x-A2.x)*(A1.x-A2.x)+(A1.y-A2.y)*(A1.y-A2.y))*sqrt((A3.x-A2.x)*(A3.x-A2.x)+(A3.y-A2.y)*(A3.y-A2.y)));
uA4=((A1.x-A4.x)*(A3.x-A4.x)+(A1.y-A4.y)*(A3.y-A4.y))/
(sqrt((A1.x-A4.x)*(A1.x-A4.x)+(A1.y-A4.y)*(A1.y-A4.y))*sqrt((A3.x-A4.x)*(A3.x-A4.x)+(A3.y-A4.y)*(A3.y-A4.y)));
//calculate angles
uA2=acos(uA2)*180.0/PI;
uA4=acos(uA4)*180.0/PI;
//the part that gives me an incorrect answer
cout<<uA2+uA4-180<<endl;
}
For floating point computation, we can use some very small offset value for marginal error, for example 1e-6.
double diff = uA2 + uA4 - 180, threshold = 1e-6;
if (diff < threshold && diff > -threshold) cout << "0" << endl;
else cout << diff << endl;
// cout<<uA2+uA4-180<<endl;
So I was trying to puzzle out how to calculate the average hue of a number of objects whose colors are represented by HSL values. Thankfully, I stumbled across this Stack Overflow post, and set to work implementing the algorithm provided in the top answer (I am working in C++).
Unfortunately, my implementation doesn't seem to work. Here it is, in full; note that though I write "Hue" I am using angles, in degrees, as per the initial implementation (switching from 0-360 angles to 0-256 hues, once I know my code works, shouldn't be hard).
#include <iostream>
#include <vector>
#include <cmath>
#define PI (4*atan(1))
int main()
{
///
/// Calculations adapted from this source:
/// https://stackoverflow.com/questions/8169654/how-to-calculate-mean-and-standard-deviation-for-hue-values-from-0-to-360
std::vector<double> Hues = {355, 5, 5, 5, 5};
//These will be used to store the sum of the angles
double X = 0.0;
double Y = 0.0;
//Loop through all H values
for (int hue = 0; hue < Hues.size(); ++hue)
{
//Add the X and Y values to the sum X and Y
X += cos(Hues[hue] / 180 * PI);
Y += sin(Hues[hue] / 180 * PI);
}
//Now average the X and Y values
X /= Hues.size();
Y /= Hues.size();
//Get atan2 of those
double AverageColor = atan2(X, Y) * 180 / PI;
std::cout << "Average: " << AverageColor << "\n";
return 0;
}
Instead of the expected answer of 3 (since 355 should be equivalent to -5 in this scheme), I get 86.9951.
Can somebody point out what I'm doing wrong? This seems very basic.
atan2 takes its arguments in reverse order. I know, annoying! So try:
double AverageColor = atan2(Y, X) * 180 / PI;
The answer it gives now is 3.00488.
Try atan2(Y, X). atan2(a,b) is similar to atan(a/b), and you need the arctangent of the average sine over the average cosine.
I am trying to port a MATLAB program to C++.
And I want to implement a left matrix division between a matrix A and a column vector B.
A is an m-by-n matrix with m is not equal to n and B is a column vector with m components.
And I want the result X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B. In other words, X minimizes norm(A*X - B), the length of the vector AX - B.
That means I want it has the same result as the A\B in MATLAB.
I want to implement this feature in GSL-GNU (GNU Science Library) and I don't know too much about math, least square fitting or matrix operation, can somebody told me how to do this in GSL? Or if implement them in GSL is too complicate, can someone suggest me a good open source C/C++ library that provides the above matrix operation?
Okay, I finally figure out by my self after spend another 5 hours on it.. But still thanks for the suggestions to my question.
Assuming we have a 5 * 2 matrix
A = [1 0
1 0
0 1
1 1
1 1]
and a vector b = [1.8388,2.5595,0.0462,2.1410,0.6750]
The solution to the A \ b would be
#include <stdio.h>
#include <gsl/gsl_linalg.h>
int
main (void)
{
double a_data[] = {1.0, 0.0,1.0, 0.0, 0.0,1.0,1.0,1.0,1.0,1.0};
double b_data[] = {1.8388,2.5595,0.0462,2.1410,0.6750};
gsl_matrix_view m
= gsl_matrix_view_array (a_data, 5, 2);
gsl_vector_view b
= gsl_vector_view_array (b_data, 5);
gsl_vector *x = gsl_vector_alloc (2); // size equal to n
gsl_vector *residual = gsl_vector_alloc (5); // size equal to m
gsl_vector *tau = gsl_vector_alloc (2); //size equal to min(m,n)
gsl_linalg_QR_decomp (&m.matrix, tau); //
gsl_linalg_QR_lssolve(&m.matrix, tau, &b.vector, x, residual);
printf ("x = \n");
gsl_vector_fprintf (stdout, x, "%g");
gsl_vector_free (x);
gsl_vector_free (tau);
gsl_vector_free (residual);
return 0;
}
In addition to the one you gave, a quick search revealed other GSL examples, one using QR decomposition, the other LU decomposition.
There exist other numeric libraries capable of solving linear systems (a basic functionality in every linear algebra library). For one, Armadillo offers a nice and readable interface:
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
int main()
{
mat A = randu<mat>(5,2);
vec b = randu<vec>(5);
vec x = solve(A, b);
cout << x << endl;
return 0;
}
Another good one is the Eigen library:
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
Matrix3f A;
Vector3f b;
A << 1,2,3, 4,5,6, 7,8,10;
b << 3, 3, 4;
Vector3f x = A.colPivHouseholderQr().solve(b);
cout << "The solution is:\n" << x << endl;
return 0;
}
Now, one thing to remember is that MLDIVIDE is a super-charged function and has multiple execution paths. If the coefficient matrix A has some special structure, then it is exploited to obtain faster or more accurate result (can choose from substitution algorithm, LU and QR factorization, ..)
MATLAB also has PINV which returns the minimal norm least-squares solution, in addition to a number of other iterative methods for solving systems of linear equations.
I'm not sure I understand your question, but if you've already found your solution using MATLAB, you may want to consider using MATLAB Coder, which automatically translates your MATLAB code into C++.