Why the counter does not work in this while loop? - while-loop

In this code, the loop is still working to compute the ratio r according to the given condition of the absolute error until getting r=1.6180 at i=16, but here it gives the result at i=3 (initial i) which means the counter does not work. what is wrong here?
clc
clear
//funcprot(0)
function f=fib(n)
f(1)=1
f(2)=1
for i=3:n
f(i)=f(i-1)+f(i-2)
end
endfunction
//n=5
//disp(fib(n))
//compute golden ration
//compute golden ration
r0=0
r1=1 //ratio y2/y1
//err=r1-r0
i=3
while abs(r1-r0)>10^(-5)
r1=r0
r=fib(i)/fib(i-1)
i=i+1
end
//f(16)/
disp(r)
Thanks S. Gougeon. Also after clearing r1=r0 from the loop, I am getting the wrong result (r is the golden ratio of fibonacci sequence=(1+sqrt(5))/2).
clc
clear
//funcprot(0)
function f=fib(n)
f(1)=1
f(2)=1
for i=3:n
f(i)=f(i-1)+f(i-2)
end
endfunction
//n=5
//disp(fib(n))
//compute golden ration
//compute golden ration
r0=0
r1=1 //ratio y2/y1
//err=r1-r0
err=1
i=3
while abs(err)>10^(-5)
//r1=r0
r=fib(i)/fib(i-1)
err=r-r0
i=i+1
end
//f(16)/
disp(r)

In the while loop, setting r1=r0 yields r0-r0=0 for the next while condition (since r0 never changes), and so escapes the while condition and loop.

Related

Leibniz formula for Pi with a given accuracy

I was asked to calculate the Pi number using the Leibniz formula for Pi with a given accuracy (eps).
The formula looks like this:
Initially, I wrote the following code:
fun main() {
val eps = 0.005
var n = 2
var r = row(n) // current row
var r0 = row(n-1)
var s = r0 + r
while (Math.abs(r) > eps) {
n++
r = row(n)
s += r
}
println(r.toString() + " <-- Leibniz(" + n.toString() + ")")
println(Math.abs(s*4).toString() + " <-- our evaluation with eps")
println(Math.PI.toString() + " <-- real Pi")
println((Math.abs(s*4)) in (Math.PI-eps..Math.PI+eps))
}
fun row(n: Int) = ((Math.pow(-1.0, n.toDouble()))/(2*n-1))
Then I found out that it doesn't work correctly, because
println((Math.abs(s*4)) in (Math.PI-eps..Math.PI+eps)) printed false.
I went deeper, made a debug, and realised that if went with
while (Math.abs(r) > eps/2)
over
while (Math.abs(r) > eps) everything works fine.
Could someone please provide any explanation on what I did wrong or why I have to divide eps by 2 if that is correct.
Thanks.
Each term r_i in that series is summed up to PI with a factor of 4 because sum(r_0, .., r_n) = PI/4. So of course, when you stop at the first r_i <= eps that only means that sum(r_0, ..., r_(i-1)) has an accuray of eps, ie it is somewhere in between [PI/4 - eps/2, PI/4 + eps/2]. But PI it self is 4*sum thus the accuracy is of course 4*eps ie the approximation lies somewhere inbetween [PI-2*eps ,PI+2*eps]
For your value of eps = 0.005:
The first r_100 = 0.00497512... is the first r <= eps
sum(r0, ..., r_99) = 0.782829, so PI at that point would be approximated as 3.1315929
EDIT
Also you are actually calculating -PI because are flipping the sign of each term in the series. So what you call r0 in your code (it should rather be called r1 because it's the result of row(1)) is -1 instead of +1
When you check Math.abs(r) > eps you're looking at the size of the n-th element of the series.
The distance of your current approximation from PI is the sum of all the terms in the series after that one.
As far as I know the relationship between the size of the n-th element of a convergent series and how good of an approximation you have depends on the specific series you are summing.

Split lines in clojure while reading from file

I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.
I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".
Here is my code so far
(defn readFile []
(map (fn [line] (clojure.string/split line #";"))
(with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
(doseq [line (line-seq rdr)]
(clojure.string/split line #";")
(println line)))))
When I do this, I still get the output:
"I;Am;A;String;"
Am I missing something?
I'm not sure if you need this at school, but since Gary already gave an excellent answer, consider this as a bonus.
You can do elegant transformations on lines of text with transducers. The ingredient you need is something that allows you to treat the lines as a reducible collection and which closes the reader when you're done reducing:
(defn lines-reducible [^BufferedReader rdr]
(reify clojure.lang.IReduceInit
(reduce [this f init]
(try
(loop [state init]
(if (reduced? state)
#state
(if-let [line (.readLine rdr)]
(recur (f state line))
state)))
(finally
(.close rdr))))))
Now you're able to do the following, given input work.txt:
I;am;a;string
Next;line;please
Count the length of each 'split'
(require '[clojure.string :as str])
(require '[clojure.java.io :as io])
(into []
(comp
(mapcat #(str/split % #";"))
(map count))
(lines-reducible (io/reader "/tmp/work.txt")))
;;=> [1 2 1 6 4 4 6]
Sum the length of all 'splits'
(transduce
(comp
(mapcat #(str/split % #";"))
(map count))
+
(lines-reducible (io/reader "/tmp/work.txt")))
;;=> 24
Sum the length of all words until we find a word that is longer than 5
(transduce
(comp
(mapcat #(str/split % #";"))
(map count))
(fn
([] 0)
([sum] sum)
([sum l]
(if (> l 5)
(reduced sum)
(+ sum l))))
(lines-reducible (io/reader "/tmp/work.txt")))
or with take-while:
(transduce
(comp
(mapcat #(str/split % #";"))
(map count)
(take-while #(> 5 %)))
+
(lines-reducible (io/reader "/tmp/work.txt")))
Read https://tech.grammarly.com/blog/building-etl-pipelines-with-clojure for more details.
TL;DR embrace the REPL and embrace immutability
Your question was "what am I missing?" and to that I'd say you're missing one of the best features of Clojure, the REPL.
Edit: you might also be missing that Clojure uses immutable data structures so
consider this code snippet:
(doseq [x [1 2 3]]
(inc x)
(prn x))
This code does not print "2 3 4"
it prints "1 2 3" because x isn't a mutable variable.
During the first iteration (inc x) gets called, returns 2, and that gets thrown away because it wasn't passed to anything, then (prn x) prints the value of x which is still 1.
Now consider this code snippet:
(doseq [x [1 2 3]] (prn (inc x)))
During the first iteration the inc passes its return value to prn so you get 2
Long example:
I don't want to rob you of the opportunity to solve the problem yourself so I'll use a different problem as an example.
Given the file "birds.txt"
with the data "1chicken\n 2duck\n 3Larry"
you want to write a function that takes a file and returns a sequence of bird names
Lets break this problem down into smaller chunks:
first lets read the file and split it up into lines
(slurp "birds.txt") will give us the whole file a string
clojure.string/split-lines will give us a collection with each line as an element in the collection
(clojure.string/split-lines (slurp "birds.txt")) gets us ["1chicken" "2duck" "3Larry"]
At this point we could map some function over that collection to strip out the number like (map #(clojure.string/replace % #"\d" "") birds-collection)
or we could just move that step up the pipeline when the whole file is one string.
Now that we have all of our pieces we can put them together in a functional pipeline where the result of one piece feeds into the next
In Clojure there is a nice macro to make this more readable, the -> macro
It takes the result of one computation and injects it as the first argument to the next
so our pipeline looks like this:
(-> "C:/birds.txt"
slurp
(clojure.string/replace #"\d" "")
clojure.string/split-lines)
last note on style, for Clojure functions you want to stick to kebab case so readFile should be read-file
I would keep it simple, and code it like this:
(ns tst.demo.core
(:use tupelo.test)
(:require [tupelo.core :as t]
[clojure.string :as str] ))
(def text
"I;am;a;line;
This;is;another;one
Followed;by;this;")
(def tmp-file-name "/tmp/lines.txt")
(dotest
(spit tmp-file-name text) ; write it to a tmp file
(let [lines (str/split-lines (slurp tmp-file-name))
result (for [line lines]
(for [word (str/split line #";")]
(str/trim word)))
result-flat (flatten result)]
(is= result
[["I" "am" "a" "line"]
["This" "is" "another" "one"]
["Followed" "by" "this"]])
Notice that result is a doubly-nested (2D) matrix of words. The simplest way to undo this is the flatten function to produce result-flat:
(is= result-flat
["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))
You could also use apply concat as in:
(is= (apply concat result) result-flat)
If you want to avoid building up a 2D matrix in the first place, you can use a generator function (a la Python) via lazy-gen and yield from the Tupelo library:
(dotest
(spit tmp-file-name text) ; write it to a tmp file
(let [lines (str/split-lines (slurp tmp-file-name))
result (t/lazy-gen
(doseq [line lines]
(let [words (str/split line #";")]
(doseq [word words]
(t/yield (str/trim word))))))]
(is= result
["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))
In this case, lazy-gen creates the generator function.
Notice that for has been replaced with doseq, and the yield function places each word into the output lazy sequence.

verilog component value passing

I am just beginning to learn verilog. I wrote two programs for that purpose. Here is my first program:
module test1(i,o);
input i;
output o;
wire[0:63] i;
wire[0:63] o;
assign o = i * 2.0;
endmodule
module test1_tb();
reg[0:63] inp;
wire[0:63] outp;
initial
begin
assign inp = 2.0;
$monitor("input=%f, output=%f",inp,outp);
end
test1 t1(inp,outp);
endmodule
This gives me the following result when I run it in ModelSim:
# input=2.000000, output=4.000000
Then I edited the above program as follows:
module test1(i1,i2,h1,w1,w2,b1);
input i1;
input i2;
input w1;
input w2;
input b1;
output h1;
wire[0:63] i1;
wire[0:63] i2;
wire[0:63] h1;
wire[0:63] w1;
wire[0:63] w2;
wire[0:63] b1;
assign h1 = 1/(1+ 2.718281828459**((-1.0)*(i1 * w1 + i2 * w2 + b1)));
endmodule
module test1_tb();
reg[0:63] i1;
reg[0:63] i2;
reg[0:63] w1;
reg[0:63] w2;
reg[0:63] b1;
wire[0:63] h1;
initial
begin
assign i1 = 0.05;
assign i2 = 0.10;
assign w1 = 0.15;
assign w2 = 0.20;
assign b1 = 0.35;
$monitor("i1=%f, i2=%f, w1=%f, w2=%f, b1=%f, h1=%f",i1,i2,w1,w2,b1,h1);
end
test1 n1(i1,i2,h1,w1,w2,b1);
endmodule
For this program I get the output:
# i1=0.000000, i2=0.000000, w1=0.000000, w2=0.000000, b1=0.000000, h1=1.000000
It seems the module does not get the initial values in the second program. But all I did was adding few more input lines to the first program and changing the calculation.
Right now I don't know what's the error with this. Please help.
The type reg is not designed to implicitly handle floating point math. As such, real constants assigned to the reg variables are rounded to the nearest integer (see IEEE1800-2012 Section 5.7.2, SystemVerilog LRM; sorry I dont have IEEE1364, Verilog LRM, to find the reference in there).
If you simply want to do some floating point math, you can use the real type which is the same as a double. Otherwise, if you want to do floating point math in hardware, youll need to deal with the complexities of it yourself (or borrow from an IP core). Also note that Verilog is not a scripting language, but a Hardware Descriptive Language, so unless you are trying to design hardware, you are much better off using Python, Ruby or Perl for general purpose stuff.

Calculate the time complexity of the following function

How do I calculate the time complexity of the following function?
int Compute (int n)
{
int j = 0;
int i = 0;
while (i<=n)
{
i = 2*j + i + 1;
j++;
}
return j-1;
}
Now, I know that the loop has O(n) time complexity, but in this case i grows in a much faster rate. Taking this iteration by iteration I found out that, for every m-th iteration i = m^2. But I'm still confused how to calculate Big-O.
If you look at the values of i and j for a few iterations:
i=1
j=1
i=4
j=2
i=9
j=3
i=16
j=4
and so on. By mathematical induction we can prove that i takes square values: ( 2*n + n^2 + 1 = (n+1)^2 )
Since we loop only while i<=n and since i takes the vales 1, 2^2, 3^2,..., k^2 <=n, it means that we stop when i=k goes over sqrt(n). Hence the complexity seems to be O(k) which means O(sqrt(n)).

What is clojure.lang.Var.getRawRoot and why is it called?

I was writing a function that checks if two points can see each other on a 2D grid for a pathfinding algorithm. After profiling the code, I found that it spent 60% of its time in clojure.lang.Var.getRawRoot(). Why is this function consuming so much time and can I optimize it away?
(defn line-of-sight-helper [^Maze maze [x0 y0] [x1 y1]]
"Determines if there is a line of sight from [x0 y0] to [x1 y1] in maze."
(let [dy (int (- y1 y0))
dx (int (- x1 x0))
sy (int (if (neg? dy) -1 1))
sx (int (if (neg? dx) -1 1))
dy (int (* sy dy))
dx (int (* sx dx))
bias-x (int (if (pos? sx) 0 -1))
bias-y (int (if (pos? sy) 0 -1))
x-long (boolean (>= dx dy))
[u0 u1 du su bias-u] (if x-long
[(int x0) (int x1) dx sx bias-x]
[(int y0) (int y1) dy sy bias-y])
[v0 v1 dv sv bias-v] (if x-long
[(int y0) (int y1) dy sy bias-y]
[(int x0) (int x1) dx sx bias-x])
grid (if x-long
#(blocked? maze [%1 %2])
#(blocked? maze [%2 %1]))]
(loop [u0 u0
v0 v0
error (int 0)]
(if (not= u0 u1)
(let [error (+ error dv)
too-much-error? (> error du)
next-blocked? (grid (+ u0 bias-u) (+ v0 bias-v))
branch3 (and too-much-error? (not next-blocked?))
v0 (int (if branch3
(+ v0 sv)
v0))
error (if branch3
(int (- error du))
(int error))]
(if (and too-much-error? next-blocked?)
false
(if (and (not (zero? error)) next-blocked?)
false
(if (and (zero? dv)
(grid (+ u0 bias-u)
v0)
(grid (+ u0 bias-u)
(- v0 1)))
false
(recur (int (+ u0 su))
v0
error)))))
true))))
What's happening with getVarRoot?
I'm really surprised that any program spends much time in getRawRoot(). All this method does is return a single field from the Var, as per the source in clojure.lang.Var:
final public Object getRawRoot(){
return root;
}
In additional, it's a small final method so should be inlined by any modern JIT compiler..... basically any calls to getRawRoot should be insanely fast.
I suspect that something strange is going on with your profiler: perhaps it is adding debug code in getRawRoot() that is taking a lot of time. Hence I'd suggest benchmarking your code without the profiler and with java -server to see how the function really performs.
Other performance hints
Make sure you use Clojure 1.3+, since there are some optimisations for var access that you will almost certainly want to take advantage of in this kind of low-level code.
If I was to take a guess as to what is actually the biggest bottleneck in this code, then I think it would be the fact that the grid function #(blocked? maze [%1 %2]) constructs a new vector every time it is called to check a grid square. It would be much better if you could refactor this so that it didn't need a vector and you could then just use #(blocked? maze %1 %2) directly. Constructing new collections is expensive compared to simple maths operations so you want to do it sparingly in you inner loops.
You also want to make sure you are using primitive operations wherever possible, and with (set! *unchecked-math* true). Make sure you declare your locals as primitives, so you will want e.g. (let [u0 (int (if x-long x0 y0)) .....] .....) etc. The main reason to do this is avoid the overhead of boxed primitives, which again implies memory allocations that you want to avoid in inner loops.