In the latest Boost, there is a function to compute the Bernoulli number, but I miss what it does exactly.
For example, Mathematica, Python mpmath and www.bernoulli.org say that:
BernoulliB[1] == -1/2
but the boost version
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/special_functions/bernoulli.hpp>
boost::multiprecision::cpp_dec_float_100 x = bernoulli_b2n<boost::multiprecision::cpp_dec_float_100>(1);
returns 0.166667
Why this difference? Am I missing something?
All odd Bernoulli numbers are zero, apart of B1, which you know is -1/2. So,
boost::math::bernoulli_b2n returns the only even (2nth) Bernoulli numbers.
For example, to get B4 you need to actually pass 2:
std::cout
<< std::setprecision(std::numeric_limits<double>::digits10)
<< boost::math::bernoulli_b2n<double>(2) << std::endl;
and if you pass 1, you get B2.
See docs: http://www.boost.org/doc/libs/1_56_0/libs/math/doc/html/math_toolkit/number_series/bernoulli_numbers.html
Of course, you can make a simple wrapper, to imitate preferred syntax1:
double bernoulli(int n)
{
if (n == 1) return -1.0 / 2.0; // one
if (n % 2) return 0; // odd
return boost::math::bernoulli_b2n<double>(n / 2);
}
int main()
{
std::cout << std::setprecision(std::numeric_limits<double>::digits10);
for (int i = 0; i < 10; ++i)
{
std::cout << "B" << i << "\t" << bernoulli(i) << "\n";
}
}
or even a class with overloaded operator[] (for demanding persons ;) ):
class Bernoulli
{
public:
double operator[](int n)
{
return bernoulli(n);
}
};
or even make use of template magic and do all this checks at compile time (I will left it as an exercise for a reader ;) ).
1Please note, that this exact function body is not well verified and can contains mistakes. But I hope you've got the idea of how you can make a wrapper.
Related
I need to program a method that will pass two int numbers i1 and i2
and return the number that has more ones in its binary representation.
This thread should help you get the binary representations
C++ - Decimal to binary converting
later with your binary arrays you can use
#include <numeric>
std::accumulate(binaryArr, binaryArr + sizeof(binaryArr)/sizeof(binaryArr[0]), 0);
to count the number of ones.
Also this really looks like solve my homework for me type of question, try reaserching and solving the problem yourself, and then asking your question with some code samples. This way you actually learn
first of all you should find way to find how many ones contains number(count_ones_binary function), and then you just use this function to solve you problem
#include <iostream>
int count_ones_binary(int x)
{
int res = 0;
while (x != 0)
{
if (x % 2 != 0)
res++;
x /= 2;
}
return res;
}
void more_ones_binary(int i1, int i2)
{
int count_i1 = count_ones_binary(i1);
int count_i2 = count_ones_binary(i2);
if (count_i1 > count_i2)
std::cout << "i1 have more ones\n";
else if (count_i1 < count_i2)
std::cout << "i2 have more ones\n";
else std::cout << "equal\n";
}
I am supposed to get the following code to display something along the lines of: "The sum of 1 to 10 is 55." (The larger number can be any number that was just the example I got.) I was given this code to use.
#include <iostream>
using namespace std;
// Compute the sum of all of the numbers from 1 to n where n
// is a natural number
// use the formula: n(n+1)/2
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
int main()
{
int sum = 0;
int maxNumber;
// get the maxNumber for the function call
cout << "Enter a whole number greater than 0" << endl;
cin >> maxNumber;
// call compute sum
compute_sum(maxNumber); // Call to compute_sum function
// display the sum calculated by the compute_sum function
cout << "The sum of 1 to " << maxNumber;
cout << " is " << sum << endl;
return 0;
}
I do not understand how funcctions work at all and do not have any idea how I would go about getting this to work. The only thing I know about this (and this is from the teacher) is that the change required is not major. "Note: If you are making major changes to the main and compute_sum funtions you are probably
doing way too much work." I have tried changing the function to an int function with a return but I could not get it to work properly (most likely due to not knowing how functions work). So can someone please help me?
The part you're missing is the return type of the function, and then to actually return that value from the function.
At the moment you have
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
A function prototype in C looks pretty much like this
<return type> <name> (<parameters>)
{
// your logic here
return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}
You want to modify your function so you are returning the integer value you're calculating inside of it
int compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
return sum_to_limit;
}
So what happens is after main runs, when the the point of execution hits
compute_sum(maxNumber);
The program flow jumps to that function and executes the code inside of it. When the function finishes, it returns the value back to where it was originally called from. So you also need to add this to store the value returned
int result = compute_sum(maxNumber);
and then make sure to output that value to the user.
You can also make the computer_sum function a little more terse my not storing a temporary variable, you can just do this
int compute_sum(int limit) // compute_sum function
{
return limit * (limit + 1) / 2;
}
I hope that helps. There's a lot more going on behind the scenes but that's the basic idea. Good luck! :)
I am at the moment trying to code a titration curve simulator. But I am running into some trouble with comparing two values.
I have created a small working example that perfectly replicates the bug that I encounter:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a, b;
a = 5;
b = 0;
for(double i = 0; i<=(2*a); i+=0.1){
b = i;
cout << "a=" << a << "; b="<<b;
if(a==b)
cout << "Equal!" << endl;
else
cout << endl;
}
return 0;
}
The output at the relevant section is
a=5; b=5
However, if I change the iteration increment from i+=0.1 to i+=1 or i+=0.5 I get an output of
a=5; b=5Equal!
as you would expect.
I am compiling with g++ on linux using no further flags and I am frankly at a loss how to solve this problem. Any pointers (or even a full-blown solution to my problem) are very appreciated.
Unlike integers, multiplying floats/doubles and adding them up doesn't produce exactly the same results.
So the best practice is find if the abs of their difference is small enough.
If you have some idea on the size of the numbers, you can use a constant:
if (fabs(a - b) < EPS) // equal
If you don't (much slower!):
float a1 = fabs(a), b1 = fabs(b);
float mn = min(a1,b1), mx = max(a1,b1);
if (mn / mx > (1- EPS)) // equal
Note:
In your code, you can use std::abs instead. Same for std::min/max. The code is clearer/shorter when using the C functions.
I would recommend restructuring your loop to iterate using integers and then converting the integers into doubles, like this:
double step = 0.1;
for(int i = 0; i*step<=2*a; ++i){
b = i*step;
cout << "a=" << a << "; b="<<b;
if(a==b)
cout << "Equal!" << endl;
else
cout << endl;
}
This still isn't perfect. You possibly have some loss of precision in the multiplication; however, the floating point errors don't accumulate like they do when iterating using floating point values.
Floating point arithmetic is... interesting. Testing equality is annoying with floats/doubles in most languages because it is impossible to accurately represent many numbers in IEEE floating point math. Basically, where you might compute an expression to be 5.0, the compiler might compute it to be 4.9999999, because it's the closest representable number in the IEEE standard.
Because these numbers are slightly different, you end up with an inequality. Because it's unmaintainble to try and predict which number you will see at compile time, you can't/shouldn't attempt to hard code either one of them into your source to test equality with. As a hard rule, avoid directly checking equality of floating point numbers.
Instead, test that they are extremely close to being equal with something like the following:
template<typename T>
bool floatEqual(const T& a, const T& b) {
auto delta = a * 0.03;
auto minAccepted = a - delta;
auto maxAccepted = a + delta;
return b > minAccepted && b < maxAccepted;
}
This checks whether b is within a range of + or - 3% of the value of a.
Is there an implementation in gmp that allows a power function with only mpf_t's as argument? I want to do this:
mpf_t s ;
mpf_init (s);
mpf_set_d (s,boost::lexical_cast<double>(sec));
mpf_t ten,mil;
mpf_init(ten);
mpf_init(mil);
mpf_set_d(ten,10.0);
mpf_set_d(mil,0.001);
mpf_div(s,s,ten);
mpf_pow_ui(s,ten,s); //<- this doesn't work because it need an unsigned int as third argument but I need it with a mpf_t
mpf_mul(s,s,mil);
I don't think so, at least not with GNU Multi-Precision library only. But you could use mpfr, which is based on gmp and supports a mpfr_pow (mpfr_t rop, mpfr_t op1, mpfr_t op2, mpfr_rnd_t rnd) function. See here.
If you decide to do that, this could also be helpful.
There is one interesting workaround using square root mpf_sqrt_ui. From math we know that x^y = Sqrt(x)^(y * 2), so we can multiply Y many times by 2 and take square root of X same amount of times.
Thus by multiplying Y by 2 you may make it almost whole integer. And as you know there is mpf_pow_ui that does powering into whole integer.
Following code does all this. Don't forget that b should be set to high precision only to allow many times square rooting.
For simplicity I used mpf_class, this is C++ interface to mpf.
I did output to console actual mpf result value and reference value computed through std::pow from .
To avoid setting high precision is a bit more difficult, but possible e.g. through Taylor Serie like
Sqrt(1 + x) = 1 + 1/2*x - 1/8*x^2 + 1/16*x^3 - 5/128*x^4 + ...
Try it online!
#include <cmath>
#include <iostream>
#include <iomanip>
#include <gmpxx.h>
int main() {
mpf_class const b0 = 9.87654321, p0 = 1.23456789;
mpf_class b = b0, p = p0;
b.set_prec(1 << 7); p.set_prec(1 << 7);
int const sqrt_cnt = 48;
for (int i = 0; i < sqrt_cnt; ++i)
mpf_sqrt(b.get_mpf_t(), b.get_mpf_t());
mpf_mul_2exp(p.get_mpf_t(), p.get_mpf_t(), sqrt_cnt);
mpf_pow_ui(b.get_mpf_t(), b.get_mpf_t(), std::lround(p.get_d()));
std::cout << std::fixed << std::setprecision(12) << "Actual "
<< b.get_d() << ", Reference " << std::pow(b0.get_d(), p0.get_d())
<< std::endl;
}
Output:
Actual 16.900803674719, Reference 16.900803674719
I have a school problem but I do not understand what it actually asks. Any of you have an idea what it's really asking for? I don't need code, I just need to understand it.
This is the problem:
Construct a computer program that uses the Secant method to solve the problem:
f(x) = (1+x) cos( sin(x)3 ) - 1.4 = 0
Starting with the initial guesses of x=2.0 and x=2.1, obtain an approximation to x such that |f(x)| < 0.0000001.
This is my code from what I understand, but I think I'm not understanding the question correctly.
#include <iostream>
#include <cmath>
double secant(double x);
using namespace std;
int main()
{
double x = 2.0;
double r = 0.0;
int counter = 0;
while( r < 0 && counter <= 40)
{
r =secant(x);
cout << "x: " << x << ", f(x): " << r << endl;
counter++;
x += 0.1;
}
return 0;
}
double secant(double x)
{
double r;
r = (1+x) * cos(pow(sin(x), 3.0)) - 1.4;
return r;
}
You are supposed to use the Secant Method: http://en.wikipedia.org/wiki/Secant_method
Follow the method as described in the article. It is an iterative method much like Netwon's method. You'll need to make a function to evaluate x(n+1) given x(n) and iterate it until your margin of error is less than specified.
The coding side of this may prove fairly straightforward as long as you know what the secant method is. Also, that page has a code example. That should prove pretty useful. :)