How can i convert a number to 0. and the number?
so
int i = 50;
float a = 0.i //wrong code :D
or what?
how can i do it?
float a = i;
while( a >= 1.0f ) a /= 10.0f;
It's ugly, but I think this works:
int i = 50;
std::stringstream ss;
ss << "0." << i;
float a;
ss >> a;
What about:
#include <cmath>
#include <initializer_list>
#include <iostream>
float zero_dot( float m ) {
return m / pow( 10.0, floor( log( m ) / log( 10.0 ) ) + 1 );
}
int main() {
for( auto const & it: { 5.0, 50.0, 500.0, 5509.0, 1.0 } ) {
std::cout << it << ": " << zero_dot( it ) << std::endl;
}
return 0;
}
The output is:
5: 0.5
50: 0.5
500: 0.5
5509: 0.5509
1: 0.1
The computation does not use any loop.
Related
I am trying to convert a small code of Matlab in c++.
In matlab normalization of random number can be done easily as below:
val = x / norm(x)
where x contains random generated real and img part between 0 and 255 as below:
70.0000000000000 + 112.000000000000i
11.0000000000000 + 97.0000000000000i
24.0000000000000 + 195.000000000000i
210.000000000000 + 203.000000000000i
177.000000000000 + 47.0000000000000i
81.0000000000000 + 125.000000000000i
243.000000000000 + 114.000000000000i
8.00000000000000 + 165.000000000000i
After the normalization, the values in val are as below:
0.126554761381164 + 0.202487618209862i
0.0198871767884686 + 0.175368740771041i
0.0433902039021132 + 0.352545406704670i
0.379664284143491 + 0.367008808005375i
0.320002753778085 + 0.0849724826416384i
0.146441938169632 + 0.225990645323507i
0.439325814508897 + 0.206103468535038i
0.0144634013007044 + 0.298307651827029i
I really donot know how to do the similar work in c++.
I thought of doing something like below but soon got stuck.
int random_real_number;
int random_img_number;
vector<int > real_number;
vector<int> img_number;
int data_size_val= 8;
srand (time(NULL)); // Initialize random seed
for(int i=0;i< data_size_val;i++){
random_real_number = rand() % 255 + 0;
std::cout << random_real_number << std::endl;
random_img_number= rand() % 255 + 0;
std::cout << random_img_number << std::endl;
real_number.push_back(random_real_number);
img_number.push_back(random_img_number);
}
It would be great help if someone can help me in it.
Thanks in advance.
The function std::norm() computes something called the field norm, which is the sum of the squares of real and imag. You get the square root of that with std::abs(). So in the same vein as the example on the C++ website, you can do:
#include <vector>
#include <cassert>
#include <complex>
#include <iostream>
#include <iomanip>
int main() {
std::vector < std::complex < double > >
zarray { { 70, 112 }, { 11, 97 }, { 24, 195 }, { 210, 203 },
{ 177, 47 }, { 81, 125 }, { 243, 114 }, { 8, 165 } };
for ( auto z: zarray ) {
assert ( std::norm ( z ) == ( z.real() * z.real() + z.imag() * z.imag() ) );
assert ( std::norm ( z ) == ( z * std::conj ( z ) ) );
// assert ( std::norm ( z ) == ( std::abs ( z ) * std::abs ( z ) ) );
std::cout << "std::abs ( " << std::setw(9) << z << " ) = "
<< std::setw(7) << std::abs ( z )
<< ", z/abs = " << std::setw(19) << z / std::abs ( z ) << '\n';
}
}
which should return
std::abs ( (70,112) ) = 132.076, z/abs = (0.529999,0.847998)
std::abs ( (11,97) ) = 97.6217, z/abs = (0.11268,0.993631)
std::abs ( (24,195) ) = 196.471, z/abs = (0.122155,0.992511)
std::abs ( (210,203) ) = 292.077, z/abs = (0.718988,0.695022)
std::abs ( (177,47) ) = 183.134, z/abs = (0.966506,0.256643)
std::abs ( (81,125) ) = 148.95, z/abs = (0.543808,0.83921)
std::abs ( (243,114) ) = 268.412, z/abs = (0.905325,0.42472)
std::abs ( (8,165) ) = 165.194, z/abs = (0.048428,0.998827)
The first complex number in your example is divided by 553.12, but I don't really see how that would be the L2-norm of 70+112i.
For the C++ experts: compared to the example I had to comment out the last assert because it fails on some of the inputs, I'm not sure why that is.
I'm running a program that preforms a Euler Approximation of an Ordinary Differential Equation. The smaller the step size that is chosen, the more accurate the approximation is. I can get it to work for a set step size using this code:
#include <iostream>
using std::cout;
double f (double x, double t)
{
return t*x*x-t;
}
int main()
{
double x=0.0,t=0.0,t1=2.0;
int n=20;
double h = (t1-t) / double(n);
// ----- EULERS METHOD
for (int i=0; i<n; i++)
{
x += h*f(x,t);
t += h;
}
cout << h << " " << x << "\n";
}
So this code runs a Eulers approximation for n=20 which corresponds to a step size of 0.1 and outputs the step size along with the approximation for x(2). I want top know how to loop this code (for different values of n) so that it outputs this followed by increasingly smaller step sizes with corresponding approximations.
i.e an output something like this:
0.1 -0.972125
0.01 -0.964762
0.001 -0.9641
etc.
So I tried a for-loop inside a for-loop but its giving me a weird output of extreme values.
#include <iostream>
using std::cout;
double f (double x, double t)
{
return t*x*x-t;
}
int main()
{
double x=0.0,t=0.0,t1=2.0;
for (int n=20;n<40;n++)
{
double h = (t1-t)/n;
for (int i=0;i<n;i++)
{
x += h*f(x,t);
t += h;
}
cout << h << " " << x << "\n";
}
}
If I understand correctly, you want to execute that first piece of code inside your main function for different values of n. Then your problem is with the variables x, t and t1, which are set once before the loop and never reset. You want them inside your outer loop:
#include <iostream>
using std::cout;
double f( double x, double t )
{
return t * x * x - t;
}
int main()
{
for ( int n = 20; n < 40; n++ )
{
double x = 0.0, t = 0.0, t1 = 2.0;
double h = ( t1 - t ) / n;
for ( int i = 0; i < n; i++ )
{
x += h * f( x, t );
t += h;
}
cout << h << " " << x << "\n";
}
}
Using a function for this, makes it clearer:
#include <iostream>
using std::cout;
double f( double x, double t )
{
return t * x * x - t;
}
void eulers( const int n )
{
double x = 0.0, t = 0.0, t1 = 2.0;
double h = ( t1 - t ) / n;
for ( int i = 0; i < n; i++ )
{
x += h * f( x, t );
t += h;
}
cout << h << " " << x << "\n";
}
int main()
{
for ( int n = 20; n < 40; n++ )
{
eulers( n );
}
}
Hope this helps.
so, I got a code and I need to express my answers into 3 columns with x,y,a in program, by compiling I only get the calculation answers - 1 column with y value throughout the cycle [5] . How do I make it to a table with x, y, a columns and their values? Do I need another for cycle? Any suggestions are appreciated.
#include < iostream>
using namespace std;
float fy(float x, float a);
int main()
{
float a[5] = { -8, -6, -4, -2, 0 }
float y = 0;
int i = 0;
for (float x = -1; x <= 1; x += 0.5)
{
cout << fy(x, a[i]) << endl;
i++;
}
cin.get();
return 0;
}
float fy(float x, float a)
{
float y = 0;
if (sin(x)*a > 0)
y = sqrt(sin(x)*a);
else
cout << "no solution\n";
return y;
}
I guess what you want is something like this:
x y a
-1 2.59457 -8
-0.5 1.69604 -6
0 -nan -4
0.5 -nan -2
1 -nan 0
Right?
Following code should do the job:
#include <iostream>
#include <math.h>
using namespace std;
float fy(float x, float a);
int main() {
float a[5] = {-8, -6, -4, -2, 0};
float y = 0;
int i = 0;
cout << "x"
<< "\t"
<< "y"
<< "\t"
<< "a" << endl;
for (float x = -1; x <= 1; x += 0.5)
{
cout << x << "\t" << fy(x, a[i]) << "\t" << a[i] << endl;
i++;
}
cin.get();
return 0;
}
float fy(float x, float a) {
float y = 0;
if (sin(x) * a > 0)
y = sqrt(sin(x) * a);
else
y = sqrt(-1);
return y;
}
The problem in your code is that you only print the result of the function. So you neither print x nor you print the a[i] value. Check the replaced cout line and you'll see how to print the other values.
What method would I use to find the roots of f(x) = 5x(e^-mod(x))cos(x) + 1 ? I have being trying the durand-kerner method but I can't get it to work. Are there any easier ways of doing it?
Here is the my code using the durand-kerner method
#include <iostream>
#include <complex>
#include <math.h>
using namespace std;
typedef complex<double> dcmplx;
dcmplx f(dcmplx x)
{
// the function we are interested in
double a4 = 5;
double a0 = 1;
return (a4 * x * exp(-x) * cos(x) )+ a0;
}
int main()
{
dcmplx p(.9,2);
dcmplx q(.1, .5);
dcmplx r(.7,1);
dcmplx s(.3, .5);
dcmplx p0, q0, r0, s0;
int max_iterations = 100;
bool done = false;
int i=0;
while (i<max_iterations && done == false)
{
p0 = p;
q0 = q;
r0 = r;
s0 = s;
p = p0 - f(p0)/((p0-q)*(p0-r)*(p0-s));
q = q0 - f(q0)/((q0-p)*(q0-r)*(q0-s));
r = r0 - f(r0)/((r0-p)*(r0-q)*(r0-s0));
s = s0 - f(s0)/((s0-p)*(s0-q)*(s0-r));
// if convergence within small epsilon, declare done
if (abs(p-p0)<1e-5 && abs(q-q0)<1e-5 && abs(r-r0)<1e-5 && abs(s-s0)<1e-5)
done = true;
i++;
}
cout<<"roots are :\n";
cout << p << "\n";
cout << q << "\n";
cout << r << "\n";
cout << s << "\n";
cout << "number steps taken: "<< i << endl;
return 0;
}
This approach makes use of the bisection method, and the fact that you can do a little math to find an upper bound for the highest zero, respectively.
Reproduced at http://ideone.com/fFLjsh
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <utility>
#define MINX (-20.0f)
//MAXX Happens to be an upper bound for all zeroes of the function...
#define MAXX (1.0f)
#define NUM_INTERVALS (1000000)
#define NUM_BISECTION_ITERATIONS (30)
using namespace std;
double f(double x){
return 5 * x * exp(-x) * cos(x) + 1;
}
double bisection_method(double x0, double x1){
for (unsigned int i = 0; i < NUM_BISECTION_ITERATIONS; i++){
double midpoint = 0.5*x0 + 0.5*x1;
f(x0) * f(midpoint) < 0 ? x1 = midpoint : x0 = midpoint;
}
return 0.5*x0 + 0.5*x1;
}
int main(int argc, char** argv){
vector<pair<double, double>> relevant_intervals;
for (unsigned int i = 0; i < NUM_INTERVALS - 1; i++){
double x0 = MINX + (MAXX - MINX) / NUM_INTERVALS * (i);
double x1 = MINX + (MAXX - MINX) / NUM_INTERVALS * (i + 1);
if (f(x0) * f(x1) < 0)
relevant_intervals.push_back(make_pair(x0, x1));
}
cout << fixed << setprecision(20);
for (const auto & x : relevant_intervals){
cout << "One solution is approximately " << bisection_method(x.first, x.second) << endl;
}
}
I am not familiar with Durand-Kerner method, but according to Wiki http://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method, it is suitable only for solving polynomial equations. Note the line in the wiki page: "The explanation is for equations of degree four. It is easily generalized to other degrees."
Your equation is not polynomial. The numerical solution will probably not converge.
Regardless of that your function f returns wrong formula: return a4 * x * exp(-abs(x)) * cos(x) + a0; (you forgot about complex modulo, i.e. abs)
and your iterations seem also wrong. They should read:
p = p0 - f(p0)/((p0-q0)*(p0-r0)*(p0-s0));
q = q0 - f(q0)/((q0-p)*(q0-r0)*(q0-s0));
r = r0 - f(r0)/((r0-p)*(r0-q)*(r0-s0));
s = s0 - f(s0)/((s0-p)*(s0-q)*(s0-r));
but even if you make these changes, the solution will not converge - it will be oscilating. The reason is probably as written above - the method is not suitable for this type of equation.
Here is my code so far. There seems to be soemthing wrong since I keep getting an incorrect answer. I am writing in a text file that is formatted:
2
3.0 1.0
2 being the size of the array and then 3.0 and 1.0 being the coefficients. Hopefully I didnt miss much in my explanation. Any help would be greatly appreciated.
Thanks
double polyeval(double* polyarray, double x, int arraySize)
{
//int result = 0;
if(arraySize == 0)
{
return polyarray[arraySize];
}
//result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
return polyarray[arraySize-1]+ (x* (polyeval(polyarray,x,arraySize-1)));
//return result;
}
int main ()
{
int arraySize;
double x;
double *polyarray;
ifstream input;
input.open("polynomial.txt");
input >> arraySize;
polyarray = new double [arraySize];
for (int a = arraySize - 1; a >= 0; a--)
{
input >> polyarray[a];
}
cout << "For what value x would you like to evaluate?" << endl;
cin >> x;
cout << "Polynomial Evaluation: " << polyeval(polyarray, x, arraySize);
delete [] polyarray;
}
the idea that if i read in a text file of that format varying in size that it will solve for any value x given by the user
Jut taking a wild guess
for (int a = arraySize - 1; a >= 0; a--)
// ^^
{
input >> polyarray[a];
}
One error is here:
for (int a = arraySize - 1; a > 0; a--)
{ //^^should be a >=0
input >> polyarray[a];
}
You are missing some entry this way.
The recursive function should look like the following:
int polyeval(double* polyarray, double x, int arraySize)
{
if(arraySize == 1)
{
return polyarray[arraySize-1];
}
return x*(polyarray[arraySize-1]+polyeval(polyarray,x,arraySize-1));
}
The problem is mainly with the definition of the polynomial coefficients.
Your code assumes a polynomial on the form:
x( p(n) + x( p(n-1) + x( p(n-2) + ... x(p(1) + p(0)))..))
This line:
result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
Should become:
result += pow(x,arraySize)*polyarray[arraySize]+polyeval(polyarray,x,arraySize-1);
This way the polynomial is defined correctly as p(n)x^n + p(n-1)x^(n-1) ... + p1 x + p0
Couldn't work out exactly what you were trying to do, or why you were using recursion. So I whipped up a non-recursive version that seems to give the right results.
#include <iostream>
using namespace std;
double polyeval(const double* polyarray, double x, int arraySize) {
if(arraySize <= 0) { return 0; }
double value = 0;
const double * p = polyarray + (arraySize-1);
for(int i=0; i<arraySize; ++i) {
value *= x;
value += *p;
p--;
}
return value;
}
int main () {
const int arraySize = 3;
const double polyarrayA[3] = {0.0,0.0,1.0}; // 0 + 0 x + 1 x^2
const double polyarrayB[3] = {0.0,1.0,0.0}; // 0 + 1 x + 0 x^2
const double polyarrayC[3] = {1.0,0.0,0.0}; // 1 + 0 x + 0 x^2
cout << "Polynomial Evaluation A f(x) = " << polyeval(polyarrayA, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation B f(x) = " << polyeval(polyarrayB, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation C f(x) = " << polyeval(polyarrayC, 0.5, arraySize)<<std::endl;
}
You can see it running here:
http://ideone.com/HE4r6x