A daily R language trick (1) - comparison of floating point numbers

the code

root<-function(x){
	a=0
	b=1
	while( a != b ){
		a = b
		b=0.5*(b + x/b)
	}
	b
}

question

The above code is used to find the root value of x. There is a very unprofessional problem here, that is the way of writing a != b .
For numeric variables, use ! = or being == is very unprofessional. For integer numbers, this will return the correct result, but due to machine precision, for floating point numbers, he "may" return an incorrect result, so in the above code, this problem will cause the program to fall into the infinite while cycle.

solution

abs(a-b)<exp(-30)

For two variables in vector form, you can use max(abs(ab))<exp(-30) to return whether all elements in the two vectors are exactly the same

PS: For n in exp(n), it can be selected as needed. For example, if the difference between two floating-point numbers is only 10 to the negative tenth power, n can be changed to -40, -50, -60..., to save trouble, you can directly choose -100 or the like, and omit trouble.

Guess you like

Origin blog.csdn.net/ptyp222/article/details/106567944