#include <iostream>
#include <math.h>
int main()
{
double result = sqrt(4732);
int intResult = (int)result;
result = result - (double)intResult;
double first = result;
while(1)
{
result = 1/result;
intResult = (int)result;
result = result - intResult;
std::cout<<intResult<<std::endl;
double absDiff = result > first ? (result-first):(first-result);
if(absDiff < 0.000001)
break;
}
return 0;
}
I am trying to calculate continued fraction of square root of 4732. Here is the wiki description for the continued fraction.
https://en.wikipedia.org/wiki/Continued_fraction
The correct answer is [68;1,3,1,3,45,1,1,2,11,15,5,34,5,15,11,2,1,1,45,3,1,3,1,136].
My code goes in an infinite loop. Here is the output from the first few iterations.
[68;1,3,1,3,45,1,1,2,11,15,5,126,..
Note that the output starts diverging from here.
I have checked this code for other numbers like 9999, 13, 12, etc. and it is giving the correct answer.
Can anybody point me to the problem in the code?
Thanks in advance.
Update: I used float128 as well. But it does not solve the issue. It looks like I may have to use some another algorithm to avoid losing precision.
Thanks to interjay for pointing me to how to solve the problem. Here is the code that gave the correct results for me. The key here is not to use floating point arithmetic as it would propagate error even if you use 128 bits of precision.
#include <iostream>
#include <math.h>
int main()
{
int num = 4732;
double result = sqrt(num);
int intResult = (int)result;
int a = intResult;
int b = 1;
int first_a = a;
int first_b = b;
do
{
double temp = (double)b/ (result - (double)a);
int I = (int)temp;
int new_a = (I*((num - (a*a))/b)) - a;
int new_b = (num - (a*a))/b;
a = new_a;
b = new_b;
std::cout<<I<<std::endl;
}
while((first_a != a) || (first_b != b));
return 0;
}
Related
I am writing some code that prints out a sum series using a loop and a function.
I intend the equation to look like this
m(i) = (1/2) + (2/3) + ... (i / i + 1)
The problem is that my code always gives me incorrect answers and not printing what it's supposed to. For example, when I input 1 into 1 the answer should be 0.5
This is my code:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
sum = (x/x + 1);
sum += sum;
}
cout<<sum;
}
Indeed, you overwrite your sum but also take care of your integer division.
You may change it as sum += i/(double)(i + 1);
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(5);
return 0;
}
void sumSeries(int x){
if (x<0)
{
return;
}
double sum = 0;
for(int i = 0; i < x; i++){
sum += i/(double)(i + 1);
}
cout<<sum;
}
I see two problems in your code.
First: (x/x+1) != (x/(x+1)), in this case C++ obeys the normal point before line calculation rules.
Second: You are overwriting your sum in each iteration, instead of that you should direct add to sum: sum+=x/(x+1)
And a third issue, as noted by Simon Kraemer, is that you are using integer division, to get the correct results you must cast at least one of the operands to a floating point number.
What you want is:
void sumSeries(int x){
double sum = 0;
for(int i = 1; i <= x; i++){ // include i in the list
sum += static_cast<double>(i)/(i + 1); // force the operation as double
}
cout<<sum;
}
your mathematical expression has something not normal. Do you mean M(i)= sum(1-i){i/i+1}? , or 1/2 and 1/3 are constants?
in your case as gerum answered it is a small Operator Precedence problem to learn how the C++ compiler prioritize the operators follow here.
your function also should have a guard against zero denominator (undefined values).
Also you should observe that you take int/int division which will ignore the remaining value. then you should consider that by converting the numerator or the denominator to double before the division here .
then your code should be:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
if ((x+1)!=0){
sum += (double)x/(x + 1);
}
// the else will apply only if x==-1
else {
cout<<"the denominator is zero"<<endl;
throw;
}
}
cout<<sum;
}
I need to write a code to calculate the following sum:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n;
cin>>n>>m;
float sum = 0.0, prod = 1.0;
int i = 2;
while(i <= n)
{
int j = 3;
while(j <= m)
{
prod = prod * (float)(i*i/j);
j++;
}
sum+=prod;
i++;
}
cout<<sum<<endl;
return 0;
}
However, getting a wrong answer and I guess it's because (float)(i*i/j) this part. It's rounding the fraction. How to fix this little problem?
Recast j:
prod = prod * (i * i / (float)j);
This will promote the product to a float.
Some rules of conversion may be useful, generally: https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}
I have the following code which calculates, for the number of terms of your choosing, the square root of 6 * [ 1 + 1/(2^2) + 1/(3^2)....1/(n^2)]. In this case, I'm going with 100 terms. If I am given what the output should be, is there a way to, using my existing code, determine how many terms were used to get to that output?
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[]) {
long double square = 0;
for (int i = 1; i <= 100; i++) {
long double squareExp = i*i;
square += 1/(squareExp);
}
long double sixTimes = 6 * square;
long double squareRoot = sqrt(sixTimes);
printf("%.8Lf", squareRoot);
return 0;
}
I tried making it so that I take the desired output (3.141592), squaring it and dividing by 6 to negative the square root and (*6), and tried running this code:
double temp = 3.141592 * 3.141592;
double tempB = temp / 6;
printf("%f\n", tempB);
int reachedZero = 0;
int valueOfN = 0;
long double square = 0;
while (square > 0) {
int i = 1;
square -= 1/i;
i++;
if (square <= 1) {
reachedZero = 1;
valueOfN = i;
break;
}
}
printf("%i", valueOfN);
return 0;
}
I can't figure out what to do. I want to take the number (after getting rid of the square root and multiplying by 6), and subtract numbers starting with 1, then 1/4, then 1/9, then 1/16...1/(n^2) until the number becomes negative. Once that happens, I set a flag and I know how many terms I needed to reach that #. I then set that specific counter to a variable, which I can print out.
#EugeneSh. This was a working solution for me. Basically matched the pi output I was looking for with my loop, checking it each time. Could have changed the for loop to a while loop but it works fine this way.
int main(int argc, const char * argv[]) {
long double square;
for (long i = 1; i>=1; i++) {
square += 1.0/(i*i);
long double sixTimes = sqrt(6 * square);
if (sixTimes >= 3.141592) {
printf("%li", i);
break;
}
}
return 0;
}
I needed to convert a fractional part of a number into integer without a comma,
for example I have 3.35 I want to get just 35 part without zero or a comma,
Because I used the modf() function to extract the the fractional part but it gives me a 0.35
if there is any way to do that or to filter the '0.' part I will be very grateful if you show me how with the smaller code possible,
A bit more efficient than converting to a string and back again:
int fractional_part_as_int(double number, int number_of_decimal_places) {
double dummy;
double frac = modf(number,&dummy);
return round(frac*pow(10,number_of_decimal_places));
}
#include <iostream>
#include <cmath>
double round(double r) {
return (r > 0.0) ? std::floor(r + 0.5) : std::ceil(r - 0.5);
}
double floor_to_zero(double f) {
return (f > 0.0) ? std::floor(f) : std::ceil(f);
}
double sign(double s) {
return (s < 0.0) ? -1.0 : 1.0;
}
int frac(double f, int prec) {
return round((f - floor_to_zero(f)) * prec) * sign(f);
}
int main() {
double a = 1.2345;
double b = -34.567;
std::cout << frac(a, 100) << " " << frac(b, 100) << std::endl; // 23 57
}
another solution
int precision= 100;
double number = 3.35;
int f = floor(xx);
double temp = ( f - number ) * -1;
int fractional_part = temp * precision;
IF you need it as a string, a quite easy C style solution would be (should work for variable number of decimal places):
double yourNumber = 0.35f;
char buffer[32];
snprintf(buffer, 32, "%g", yourNumber);
strtok(buffer, "."); // Here we would get the part before . , should still check
char* fraction = strtok(NULL, ".");
int fractionAsInt = atoi(fraction);
This example lacks error handling in case of a bad string and is not feasible if you just need a fixed number of decimal places, since the arithmetic approaches work better there.
Something like this should work:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static int get_frac(double value, unsigned short precision)
{
return (int)((value - (long)value) * pow(10, precision));
}
static int get_frac_no_trailing_zeros(double value, unsigned short precision)
{
int v = get_frac(value, precision);
while (v % 10 == 0)
v /= 10;
return v;
}
int main(int argc, char *argv[])
{
double v;
v = 123.4564;
printf("%.4f = %d\n", v, get_frac(v, 2));
printf("%.4f = %d\n", v, get_frac(v, 4));
printf("%.4f = %d\n", v, get_frac(v, 6));
printf("%.4f = %d\n", v, get_frac_no_trailing_zeros(v, 6));
return EXIT_SUCCESS;
}
You may also want to either avoid calling pow by having a user supply a number in a power of 10 in a first place, or use a lookup table.
Using some stl magic, here is the sample code:
typedef std::pair<int, int> SplitFloat;
SplitFloat Split(float value, int precision)
{
// Get integer part.
float left = std::floor(value);
// Get decimal part.
float right = (value - left) * float(std::pow(10, precision));
return SplitFloat(left, right);
}
It can be improved, but is pretty straightforward.
I just did something close to what you are trying to do, though I'm still pretty new. None the less, maybe this will help someone in the future as I landed here looking for results for my problem.
The first step is making sure that the variable that contains 3.35 is a double, but that's probably obvious.
Next, create a variable that is only an integer and set it's value equal to the value of the double. It will then only contain the whole number.
Then subtract the whole number (int) from the double. You will be left with the fraction/decimal value. From there, just multiply by 100.
Beyond the 100ths decimal value, you would have to do a little more configuring obviously, but it should be fairly simple to do with an if statement. If the decimal value is greater than .99, multiply 1000 instead etc..
Here's how I would do it.
#include <sstream>
#include <string>
int main()
{
double d = yourDesiredNumber; //this is your number
std::ostringstream out;
out << setprecision(yourDesiredPrecision) << std::fixed
<< std::showpoint << d;
std::istringstream in(out.str());
std::string wholePart; //you won't need this.
int fractionalPart;
std::getline(in, wholePart, '.');
in >> fractionalPart;
//now fractionalPart contains your desired value.
}
I'm pretty sure that instead of two different istringstream and ostringstream objects you could have gotten away with just one stringstream object, but I am not sure about the details (never used that class) so I didn't use it in the example.