Newton Raphson for Cube Root (Precision Error in Double) - c++

I am trying to implement Newton Raphson in C++.
Approach: In my root() function my while(temp-e>0) exists even when temp==e. I know it is due to using doubles and comparing double might give precision errors sometimes. But still I want to know how can I make sure that the loop exists only when temp==0. Error occurring in the test case 64. My code is returning 4.000001, while it should return 4.000000.
Code:
#include<stdio.h>
double root(int n)
{
double x=n,a,b,e=0.000001,temp;
a=2*x;
b=n/(x*x);
temp=1;
while(temp-e>0)
{
x=(a+b)/3;
a=2*x;
b=n/(x*x);
temp=(n/(x*x)-x)/3;
temp=temp<0?-temp:temp;
}
return x;
}
int main()
{
printf("%lf\n",root(64));
return 0;
}
While this code is giving correct answer, where I am doing two more iterations from where temp starts failing:
#include<stdio.h>
double root(int n)
{
double x=n,a,b,e=0.000001,temp;
a=2*x;
b=n/(x*x);
int i=0;
temp=1;
while(i<=2)
{
x=(a+b)/3;
a=2*x;
b=n/(x*x);
temp=(n/(x*x)-x)/3;
temp=temp<0?-temp:temp;
if(temp<e)
i++;
}
return x;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%lf\n",root(n));
}
return 0;
}

Related

Data type mismatch results in Runtime Error in C++

I am writing a code to calculate kth root using binary search.
#include <iostream>
#include<math.h>
using namespace std;
bool isPossible(long n,int k,long mid)
{
long ans=pow(mid,k);
if(ans<=n)
{
return true;
}
return false;
}
int main() {
int t,k;
long n;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n>>k;
int s=1;
long e=n;
long answer=n;
while(s<=e)
{
long mid=(s+e)/2;
if(isPossible(n,k,mid))
{
answer=min(answer,mid);
s=mid+1;
}
else
{
e=mid-1;
}
}
cout<<answer<<endl;
}
}
This code results in Permission denied
collect2.exe: error: ld returned 1 exit status
If I modify data type of ans in isPossible() function to double program run successfully, or if I modify the check statement to
if(pow(mid,k)<=n)
{
return true;
}
I haven't seen this kind of error because of data type mismatch, I do not understand why this happens here, cause normally storing return value of pow() in int does not cause this type of error.

Finding LCS using DP

I have used Dynamic Programming to find longest common sub-sequence b/w two strings. What is wrong in the code. Why it always gives answer as 0?
#include<bits/stdc++.h>
using namespace std;
int dp[20][20];
void initialize()
{
for(int i=0;i<20;i++)
for(int j=0;j<20;j++)
dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
if(m==0||n==0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
if(a[m-1]==b[n-1])
return dp[m-1][n-1] = 1+lcs(a,b,m-1,n-1);
if(a[m-1]!=b[n-1])
return dp[n-1][m-1]=max(dp[n][m-1]=lcs(a,b,n,m-1),dp[n-1][m]=lcs(a,b,n-1,m));
}
int main()
{
string a="AGGTAB",b="GXTXAYB";
cout<<lcs(a,b,a.length(),b.length());
}
You've forgotten to call initialize()
18th line, it should be dp[m][n], not dp[m-1][n-1]
Commented 19th line code, as it is no need & for make the code compatible for all compilers
i.e., some compiler may give warning: control reaches end of non-void function [-Wreturn-type]
Made some code change in 20th line, as it seems you confused with variables m & n.
Code:
#include<bits/stdc++.h>
using namespace std;
int dp[20][20];
void initialize()
{
for(int i=0;i<20;i++)
for(int j=0;j<20;j++)
dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
if(m==0||n==0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
if(a[m-1]==b[n-1])
return dp[m][n] = 1+lcs(a,b,m-1,n-1);
//if(a[m-1]!=b[n-1])
return dp[m][n]=max(lcs(a,b,m-1,n),lcs(a,b,m,n-1));
}
int main()
{
string a="AGGTAB",b="GXTXAYB";
initialize();
cout<<lcs(a,b,a.length(),b.length());
}
Output:
4

Hello, This simple C++ script pops out an error at line 11. Does anybody know how to fix it?

Description
This code is intended to find a spanner index (i) when dealing with
Splines/NURBS basis functions based on a knot vector (U), a choosen knot (u), the degree of the desired curve (p) and the number of basis funcions (n). The algorithm was taken from the NURBS Book by Piegl and Tiller. The error, I guess, is in the way I declared variable U. Thaks in advanced!
code
# include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(n,p,u,U) /* an error in this line */
{
if (u==U[n+1]) return (n);
low=p; high=n+1;
mid=(low+high)/2
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2
}
return (mid);
}
You have forgotten some semicolons and types!
here is the correct code:
#include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(int n, int p, int u, int U[])
{
if (u==U[n+1]) return (n);
int low=p, high=n+1;
int mid=(low+high)/2;
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2;
}
return (mid);
}
int main() {
cout << FindSpan(n, p, u, U);
return 0;
}

Different results with same function and argument in c++ code

I've made a function that calculate chebyshev moment for an image, here is the main code. I have different results with same image, and every time I run I get new values. Here is the functions and the main code.
float calcul_ro(int p,int N)
{int i; float ro_p=1,float_N=(float)N;
if (p==0)
ro_p=(float)N;
else {
for (i=1;i<=p;i++)
ro_p=ro_p*(1-((i*i)/(N*N)));
ro_p=(ro_p*float_N)/(2*p+1);
}
return ro_p;
}
///______________________________________________________________________________///
float calcul_tp(int x,int p,int N,float tp_1,float tp_2)
{float tp, float_N=(float)N;
if (p==0)
tp=1;
else if(p==1)
tp=2*x+1-N;
else
{ //tp=((2*p-1)*tp_1)-((p-1)*(1-(pow((float)(p-1),2)/pow(float_N,2)))*tp_2);
tp=((2*p-1)*tp_1)-(((p-1)*(1-((p-1)*(p-1))/(N*N)))*tp_2);
tp=tp/p;}
return tp;
}
///______________________________________________________________________///
float *chebychev_moment(Mat image,int N)
{int p,q,x=0,y=0,i=0,j,compt=0,hml=0; float rslt,alpha_p,alpha_q,beta_p,beta_q,ro_p=1,ro_q=1,tp,tq;
float *vect=new float[55];
float tp_moins_1[100][100], tp_moins_2[100][100], tq_moins_1[100][100],tq_moins_2[100][100];
///******************************************************************
///initialisation de tp_moins_1
for(i=0;i<100;i++)
{
for(j=0;j<100;j++)
tp_moins_1[i][j]=1;
}
///************************************************************************
for (p=0;p<9;p++)
{
for(i=0;i<100;i++)
{
for(j=0;j<100;j++)
tq_moins_1[i][j]=1;
}
for(q=0;q<=9-p;q++)
{
ro_p=calcul_ro(p,N);
ro_q=calcul_ro(q,N);
///************************************
for (x=0;x<image.rows;x++)
{ y=0;
tp=calcul_tp(x,p,N, tp_moins_1[x][y], tp_moins_2[x][y]);
tp_moins_2[x][y]=tp_moins_1[x][y];
tp_moins_1[x][y]=tp;
for(y=0;y<image.cols;y++)
{ if(image.at<int>(x,y)!=0)
{tq=calcul_tp(y,q,N,tq_moins_1[x][y],tq_moins_2[x][y]);
tq_moins_2[x][y]=tq_moins_1[x][y];
tq_moins_1[x][y]=tq;
rslt=rslt+tp*tq*image.at<int>(x,y);}
}
}
///************************
rslt=rslt*(1/(ro_p*ro_q));
printf("rslt %d ,p=%d,q=%d, =%f \n",hml,p,q,rslt);
vect[compt]=rslt;
compt++;
rslt=0;
}}
return vect;
}
///______________________________________________________________________________///
int main()
{ Mat image=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);
float *vect=new float[55], *vect2=new float[55];
vect=chebychev_moment(image,100);
Mat image2=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);
vect2=chebychev_moment(image2,100);
//function that copy the vector in a file
write_on_file(vect,"vector_image3.txt");
write_on_file(vect2,"vector_image4.txt");
return 0;}
Can someone please help me?
Looks like rslt in chebychev_moment is used before it is set. Probably you forgot to initialise it to 0. alpha_p, alpha_q, beta_p, beta_q are not used at all.

Binary Search with few modification

While I am trying to compile the code with few modification in binary search recursive function. The program is acting weird. Some time it gives the correct value and some time it goes to infinite loop. Please explain what went wrong with the code. I am using DEV C++ as an IDE.
CODE:
#include<iostream>
#include<sstream>
using namespace std;
//function to compare the two integers
int compare(int low, int high)
{
if (low==high)
return 0;
if (low<high)
return 1;
else
return -1;
}
//Function for binary search using recursion
int *BinarySearch(int *Arr,int Val,int start,int end)
{
int localstart=start;
int localend=end;
int mid=(start+end)/3;
cout<<"MID:"<<mid;
int comp= compare(Val,Arr[mid]);
if(comp==0)
return &(Arr[mid]);
else if (comp>0)
return BinarySearch(Arr,Val,localstart,mid-1);
else
return BinarySearch(Arr,Val,mid+1,localend);
return NULL;
}
main()
{
int *arr;
arr= new int [256];
string str;
getline(cin,str);
stringstream ss;
ss<<str;
int index=0;
while(ss>>arr[index])
{index++;}
//cout<<arr[index-1];
cout<<"Enter Value:";
int value;
cin>>value;
int *final;
final=BinarySearch(arr,value,0,index-1);
if(final!=NULL)
cout<<"Final:"<<*final;
else
cout<<"Not Found";
getchar();
getchar();
return 0;
}
Two ideas:
What should BinarySearch do if Val is not in the array? Trace out what your code does in this case.
(start+end)/3 probably isn't the middle of the current range.