[R] how to get all iterations if I meet NaN?
Patrizio Frederic
frederic.patrizio at gmail.com
Fri Mar 27 22:59:33 CET 2009
2009/3/27 huiming song <huimings at gmail.com>:
> hi, everybody, please help me with this question:
>
> If I want to do iteration for 1000 times, however, for the 500th iteration,
> there is NaN appears. Then the iteration will stop. If I don't want the stop
> and want the all the 1000 iterations be done. What shall I do?
>
>
> suppose I have x[1:1000] and z[1:1000],I want to do some calculation for all
> x[1] to x[1000].
>
> z=rep(0,1000)
> for (i in 1:1000){
> z[i]=sin(1/x[i])
> }
>
> if x[900] is 0, in the above code it will not stop when NaN appears. Suppose
> when sin(1/x[900]) is NaN appears and the iteration will now fulfill the
> rest 100 iterations. How can I write a code to let all the 1000 iterations
> be done?
>
not sure I properly understood. Consider:
x = seq(-pi,pi,length=1001)
z = sin(1/x)
# Warning message:
# In sin(1/x) : NaNs produced
x[500:502]; z[500:502]
# [1] -0.006283185 0.000000000 0.006283185
# [1] -0.8754095 NaN 0.8754095
one NaN and one warning have been created, the remaining 1000
calculations has been executed.
lim(x->0)sin(1/x) not exists so sin(1/0) is not a number nan
z1 = z[!is.nan(z)]
x1 = x[!is.nan(z)]
# x and z without the z's nan position
hope that help
Patrizio
More information about the R-help
mailing list