[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
NaN error
From: |
John W. Eaton |
Subject: |
NaN error |
Date: |
Tue, 11 Jan 2011 13:52:22 -0500 |
On 11-Jan-2011, Los Griegos Engineering wrote:
| Hello all,
|
| I came across the 196 algorithm at:
| http://mathworld.wolfram.com/196-Algorithm.html
|
| I decided to code a version of it, and it works... until I increase the
| iterations past a limit. I think the error is in the memory, but I'm
| just not sure where the error is.
|
| function [ a ] = rev (a,iter)
|
|
| for k=1:iter
|
| a=num2str(a);
| b=[];
|
| for i=length(a):-1:1
| j=length(a)-i+1;
| b(j)=a(i);
| endfor
|
| b=str2double(b);
| a=str2double(a);
|
| a=b+a;
|
| endfor
| endfunction
|
| The results I get are:
| octave-3.2.3> rev(123,1)
| ans = 444
| octave-3.2.3> rev(123,10)
| ans = 1354353
| octave-3.2.3> rev(123,11)
| ans = NaN
|
| octave-3.2.3> rev(12,11)
| ans = 175857
| octave-3.2.3> rev(12,14)
| ans = NaN
| octave-3.2.3>
|
| Is the error due to the memory address of the character array?
| GNU Octave, version 3.2.3
| Octave was configured for "i486-pc-linux-gnu".
You can write your function as
function a = rev (a, iter)
for k = 1:iter
a = num2str (a);
b = fliplr (a);
b = str2double (b);
a = str2double (a);
a = b + a;
endfor
endfunction
to avoid the inner loop. If I modify it as follows to see what the
arguments to str2double are, and what the result of the call to
str2double is
function a = rev (a, iter)
for k = 1:iter
a = num2str (a);
b = fliplr (a);
bs = char (b)
b = str2double (b)
as = char (a)
a = str2double (a)
a = b + a;
endfor
endfunction
I see
octave> rev (123, 11)
bs = 627627
b = 627627
as = 726726
a = 726726
bs = 60+e53453.1
b = NaN
as = 1.35435e+06
a = 1354350
ans = NaN
so the problem appears to bee that num2str starts returning numbers
formatted as floating point constants, and when the characters are
reversed you get something like "60+e53453.1" which is not a number.
Octave doesn't have arbitrary precision integers, so using built-in
data types here, you will hit a limit at some point no matter what you
do.
jwe
- NaN error, Los Griegos Engineering, 2011/01/11
- Re: NaN error, Francesco Potortì, 2011/01/11
- NaN error,
John W. Eaton <=