I have an error in my while condition, what to do? - fortran95

I'm getting a lot of trouble in this program
This Fibonacci sequence should stop when the difference between the division of two consecutive numbers and the aurea ratio is smaller than 10e-6.
Unfortunately, the program goes automatically to pause status, so I assume there's something going on in my while condition. Any suggestions?
program fibonacci
implicit none
integer::a,b,c,i
real::dif
real,parameter::e=10e-6,aurea=((1+sqrt(5.))/2.)
a=0;
b=1;
i=0;
dif=0;
do while (dif<e)
dif=abs((b/a)-aurea)
if (i==0) then
print*, a
else if (i==1) then
print*,b
else
c=a+b
print*,c
a=b
b=c
end if
end do
pause
end program fibonacci

Related

Call stack has exceeded maximum of depth of 100 ,Lua

function findWord(s,i)
-- find first word in given text
local j = i+1
while not _isWhite(s:byte(j)) and j < #s do -- getting error here
j = j + 1
end
return s:sub(i,j), j
end
function splitText(s,maxLen)
-- split text into chunks of maxLen length
rs ={}
local function _g(s,i,c,rs)
-- recursively split text
local function _f(s,i,c)
-- recursively find words and add each word to a chunk
local w,i = findWord(s,i)
if i == #s then return c..w end
if #(c..w) <= maxLen then
c = c..w
s = s:sub(i+1,#s,true)
return _f(s,1,c)
else
return c
end
end
rs[#rs+1] = _f(s,1,'')
i = i+#rs[#rs]
if i < #s then
local s = s:sub(i,#s,true)
return _g(s,1,'',rs)
else
return rs
end
end
return _g(s,1,'',rs)
end
I have above function to split a string, It has been working earlier but this time it started giving error "call stack has exceeded maximum of depth of 100, verify a function is not calling itself by accident."
Any idea why I might be getting this error, this behaviour seems random since I am quite sure about rest of the script and same split function has been working fine as well.
EDIT:
Yes, isWhiteSpace was provided to me and has the following code, I am not supposed to change it since it worked earlier . Here is isWhite function:
function _isWhite(byte)
return byte == 32 or byte == 9
end
So both _g and _f call themselves, and _g calls _f. So clearly the recursion-stop conditions you have are too weak. In _g I see
if i < #s then
local s = ...
return _g(s,1,'',rs)
else
return rs
end
which will stop when i >= #s. If this never happens, you will get infinite recursion. It is hard to say by looking at the code how i varies, but based on this line:
i = i+#rs[#rs]
it appears to by some value, but can't say if there is guarantee that stop condition will ever be reached. With _f it is worse: the stop recursion conditions are
if i == #s then return c..w end
and
#(c..w) > maxLen
Again very hard to say if this is strong enough: what if i is greater than #s, does the rest of the function work? Although findWord() returns i<#s for non empty s, not sure what will happen if s empty.
Best way to find out is to put some print statements that give you a trace of _g and _f and the parameters received, this will tell you clearly what stop conditions are being missed.

Lua Coroutine Error

I'm currently working on a simple 'guess the number' game using Lua. I'm programming through an app on my iPad called TouchLua+. One of the game modes is you have a certain amount of time to guess the number. I thought that to do this, I would create a coroutine that counts down from the given time. For some reason, I can't input a number while the coroutine is running. Can anyone help? Here is what I have so far.
target = math.random(1, 100)
coroutine.resume(coroutine.create(function()
for i = 1, roundTime do
sleep(1000)
sys.alert("tock")
end
lose = true
coroutine.yield()
end))
repeat
local n = tonumber(io.read())
if (n > target) then
print("Try a lower number.\n")
elseif (n < target) then
print("Try a higher number.\n")
else
win = true
end
until (lose or win)
return true
Coroutines are not a form of multiprocessing, they are a form of cooperative multithreading. As such, while the coroutine is running, nothing else is running. A coroutine is meant to yield control back to the caller often, and the caller is meant to resume the coroutine so the coroutine can continue where it yielded. You can see how this will appear to be parallel processing.
So in your case you would want to yield from inside the loop, after a small sleep time:
co = coroutine.create(function()
for i = 1, roundTime do
sleep(1)
sys.alert("tock")
coroutine.yield()
end
lose = true
end)
Unfortunately, you can't interrupt io.read(), which means the above is of no use. Ideally you would want a "io.peek" function so you could do the following:
while coroutine.status(co) ~= "dead" do
coroutine.resume(co)
if io.peek() then -- non-blocking, just checks if a key has been pressed
... get the answer and process ...
end
end
I am not aware of a non-blocking keyboard IO in Lua. You could create a C extension that exposes some of C non-blocking keyboard input to Lua, assuming that TouchLua+ supports C extensions. I doubt it, given that it is an iOS app.
It doesn't appear that there is a time loop or callbacks or such, and couldn't find docs. If you have option of creating a text box where user can enter answer and they have to click accept then you can measure how long it took. If there is a time loop you could check time there and show message if run out of time. All this is very easy to do in Corona, maybe not possible in TouchLua+.

Losing precision in Lua

I have a function in lua, which is given 2 vectors, return the lambda multiplier of first vector to second one, here is my code
function Math.vectorLambda( v1,v2 )
local v1Length,v2Length=math.sqrt(v1.x^2+v1.y^2),math.sqrt(v2.x^2+v2.y^2)
if v1Length==0 then
return nil
else
local dotProduct=v1.x*v2.x+v1.y*v2.y
print(dotProduct,v1Length,v2Length,math.abs(dotProduct)==(v1Length*v2Length))
if math.abs(dotProduct)==(v1Length*v2Length) then
if v1.x~=0 then
return v2.x/v1.x
else
return v2.y/v1.y
end
else
return nil
end
end
end
However, if
--this is what I get from terminal and I believe that it does not display the whole number--
v1={0.51449575542753,-0.85749292571254}
v2={-10,16.666666666667}
the output is
-19.436506316151 1 19.436506316151 false
which is saying the absolute value of dotProduct and v1Length*v2Length are not the same...
What is the reason for above, rather than I am blind? :(
BTW, the function is not stable..with exactly the same vectors, the function might has the same output except math.abs(dotProduct)==(v1Length*v2Length) gives true and hence return correct answer rather than nil, why?
Floats are tricky. You most likely have differences on the smaller decimal places (I don't know for sure, since I get true here). Try printing the numbers with a bigger precision, using a function like:
function prec_print(v, prec)
local format = '%.' .. prec .. 'f'
print(string.format(format, value))
end
In any case, you should almost never use == to compare floating point equality. For floats, it's quite easy to get false for simple things like a+b-b==a. What you should probably do is to check whether de difference of the two values is less than some threshold:
function almost_equal(float1, float2, threshold)
return math.abs(float1 - float2) <= threshold
end
But it's actually trickier than that (if, say, float1 and float2 are too far apart). Anyway, this read is mandatory for anyone working with floats: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Cheers!

if input is nth term in fibonacci series, finding n

in fibonacci series let's assume nth fibonacci term is T. F(n)=T. but i want to write a a program that will take T as input and return n that means which term is it in the series( taken that T always will be a fibonacci number. )i want to find if there lies an efficient way to find it.
The easy way would be to simply start generating Fibonacci numbers until F(i) == T, which has a complexity of O(T) if implemented correctly (read: not recursively). This method also allows you to make sure T is a valid Fibonacci number.
If T is guaranteed to be a valid Fibonacci number, you can use approximation rules:
Formula
It looks complicated, but it's not. The point is: from a certain point on, the ratio of F(i+1)/F(i) becomes a constant value. Since we're not generating Fibonacci Numbers but are merely finding the "index", we can drop most of it and just realize the following:
breakpoint := f(T)
Any f(i) where i > T = f(i-1)*Ratio = f(T) * Ratio^(i-T)
We can get the reverse by simply taking Log(N, R), R being Ratio. By adjusting for the inaccuracy for early numbers, we don't even have to select a breakpoint (if you do: it's ~ correct for i > 17).
The Ratio is, approximately, 1.618034. Taking the log(1.618034) of 6765 (= F(20)), we get a value of 18.3277. The accuracy remains the same for any higher Fibonacci numbers, so simply rounding down and adding 2 gives us the exact Fibonacci "rank" (provided that F(1) = F(2) = 1).
The first step is to implement fib numbers in a non-recursive way such as
fib1=0;fib2=1;
for(i=startIndex;i<stopIndex;i++)
{
if(fib1<fib2)
{
fib1+=fib2;
if(fib1=T) return i;
if(fib1>T) return -1;
}
else
{
fib2+=fib1;
if(fib2=T) return i;
if(fib2>t) return -1;
}
}
Here startIndex would be set to 3 stopIndex would be set to 10000 or so. To cut down in the iteration, you can also select 2 seed number that are sequential fib numbers further down the sequence. startIndex is then set to the next index and do the computation with an appropriate adjustment to the stopIndex. I would suggest breaking the sequence up in several section depending on machine performance and the maximum expected input to minimize the run time.

math.fmod always euqls math.mod?

I tried to figure out the difference between math.fmod and math.mod with the following code:
a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
if math.fmod(a[i],b[i])~=math.mod(a[i],b[i]) then
print("yeah")
end
end
It never prints "yeah"!
What should I put in array a and b to see "yeah"?
The documentation of math.fmod() say that it returns the remainder of the division of x by y that rounds the quotient towards zero.
math.mod is the same function as math.fmod. Actually, math.mod exists only for compatibility with previous versions; it's not listed in the manual. Try math.modf instead of math.mod in your code.
Modulo in Lua is defined as "the remainder of a division that rounds the quotient towards minus infinity" -Link here - Which is different from the definition of fmod (as you quoted in your original post).
What you really need to do is use the modulo operator (%) rather than math.mod:
a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
if math.fmod(a[i],b[i]) ~= a[i] % b[i] then
print("yeah")
end
end

Resources