The question is the root of equation x*e^x=cos(x) in 7th iteration becomes _____
ID: 3883517 • Letter: T
Question
The question is the root of equation x*e^x=cos(x) in 7th iteration becomes ______
My code is following, I don't know what's wrong? How can I modify it? I am a newman in R. Thanks :)
g<-function(x){
x*exp(x)-cos(x)
}
gPrime<-function(x){
exp(x)*(1+x)+sin(x)
}
guess<-1
tolerance<-0.0000001
n.max=100
root<-function(g,gPrime,guess,tolerance,n.max){
x=guess
n=1
# while loop
while(abs(g(x)>tolerance))&(n<n.max)){
x=x-g(x)/gPrime(x)
n<-n+1
}
if (n==7){
cat("newton failed to converge ")}
}
root(g,gPrime,guess,tolerance)
Explanation / Answer
g<-function(x)
{
x*exp(x)-cos(x)
}
gPrime<-function(x)
{
exp(x)*(1+x)+sin(x)
}
guess<-1
tolerance<-0.0000001
n.max=100
root<-function(g,gPrime,guess,tolerance,n.max)
{
x=guess
n=1
# while loop
while(abs(g(x)>tolerance) && (n<n.max)) //wrong declaration of while was there
{
x=x-g(x)/gPrime(x)
n<-n+1
}
if (n==7)
{
cat("newton failed to converge ")
}
x //x was needed to print the value of x in output
}
root(g,gPrime,guess,tolerance,n.max) //n.max parameter was missing
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.