<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>My Notes From My Notebook &#187; Just Blogging around</title>
	<atom:link href="http://www.codedanger.com/caglar/feed" rel="self" type="application/rss+xml" />
	<link>http://www.codedanger.com/caglar</link>
	<description>My Blog On Mars</description>
	<lastBuildDate>Fri, 25 Nov 2011 07:29:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Online Supplementary Mathematics Materials for Machine Learning and Artificial Intelligence Courses</title>
		<link>http://www.codedanger.com/caglar/archives/1198?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=online-supplementary-mathematics-materials-for-machine-learning-and-artificial-intelligence-courses</link>
		<comments>http://www.codedanger.com/caglar/archives/1198#comments</comments>
		<pubDate>Tue, 04 Oct 2011 06:48:47 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Engineering]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[calculus]]></category>
		<category><![CDATA[courses]]></category>
		<category><![CDATA[linear algebra]]></category>
		<category><![CDATA[numerical analysis]]></category>
		<category><![CDATA[probability and statistics]]></category>
		<category><![CDATA[supplementary documents]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=1198</guid>
		<description><![CDATA[Recently I&#8217;ve started to see a lot of questions regarding to the &#8220;mathematics tutorials or supplementary materials for Machine Learning and AI&#8221; in the online discussions with the emergence of Stanford&#8217;s online AI and machine learning courses. As with the internet crowd, I&#8217;m going to participate these courses as well and I&#8217;ve always found the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve started to see a lot of questions regarding to the &#8220;mathematics tutorials or supplementary materials for Machine Learning and AI&#8221; in the online discussions with the emergence of Stanford&#8217;s online AI and machine learning courses. As with the internet crowd, I&#8217;m going to participate these courses as well and I&#8217;ve always found the resources provided in this post as being useful for revising my math knowledge. Hence I thought that those might be useful for other folks as well. Probably a having look at only one resource in each category will be more than enough for an introductory level ML/AI course (you can skip some categories which might have less significance for an introductory level ML and AI course, e.g.: skip diff eqs, numerical analysis and study more to the probability and stats):</p>
<h2>Linear Algebra</h2>
<ul>
<li>D. Barber&#8217;s Matrices Notebook &#8211; <a href="http://www.ucl.ac.uk/Mathematics/geomath/level2/mat/MHma.html">http://www.ucl.ac.uk/Mathematics/geomath/level2/mat/MHma.html</a></li>
<li>Edinburgh&#8217;s Learning for Data course&#8217;s Linear Algebra inclined Mathematics Supplementary document for ML &#8211; <a href="http://www.inf.ed.ac.uk/teaching/courses/lfd/lfd_supp_maths2005.pdf">http://www.inf.ed.ac.uk/teaching/courses/lfd/lfd_supp_maths2005.pdf</a></li>
<li>A basic Linear Algebra Tutorial - <a href="http://tutorial.math.lamar.edu/Classes/LinAlg/LinAlg.aspx">http://tutorial.math.lamar.edu/Classes/LinAlg/LinAlg.aspx</a></li>
<li>Notes on Numeric Linear Algebra &#8211; <a href="http://gbenthien.net/NumLinAlg.pdf">http://gbenthien.net/NumLinAlg.pdf</a> </li>
</ul>
<h2>Calculus</h2>
<ul>
<li>MIT OCW Calculus Revisited &#8211; A great short course for revision of Calculus knowledge- <a href="http://ocw.mit.edu/resources/res-18-006-calculus-revisited-fall-2010/">http://ocw.mit.edu/resources/res-18-006-calculus-revisited-fall-2010/</a></li>
</ul>
<h2>Multivariable Calculus</h2>
<ul>
<li>Calculus 2 Notes &#8211; <a href="http://tutorial.math.lamar.edu/Classes/CalcII/CalcII.aspx">http://tutorial.math.lamar.edu/Classes/CalcII/CalcII.aspx</a></li>
</ul>
<h2>Probability and Statistics</h2>
<ul>
<li>Probability Notebook: <a href="http://www.ucl.ac.uk/Mathematics/geomath/level2/prob/MHpb.html">http://www.ucl.ac.uk/Mathematics/geomath/level2/prob/MHpb.html</a></li>
<li>Probability Part in McKay&#8217;s &#8220;Information Theory, Inference, and Learning Algorithms&#8221; Book &#8211; <a href="http://wol.ra.phy.cam.ac.uk/mackay/itprnn/book.html">http://wol.ra.phy.cam.ac.uk/mackay/itprnn/book.html</a></li>
<li>Probability Theory Review For Machine Learning - <a href="http://see.stanford.edu/materials/aimlcs229/cs229-prob.pdf">http://see.stanford.edu/materials/aimlcs229/cs229-prob.pdf</a></li>
<li>Probability and Statistics Review for Machine Learning - <a href="http://cs.nyu.edu/~roweis/notes/mlss05.pdf">http://cs.nyu.edu/~roweis/notes/mlss05.pdf</a></li>
</ul>
<h2>Differential Equations</h2>
<ul>
<li> Interactive Mathematics, Introduction to Differential Equations: <a href="http://www.intmath.com/differential-equations/des-intro.php">http://www.intmath.com/differential-equations/des-intro.php</a></li>
</ul>
<h2> Numerical Analysis</h2>
<ul>
<li>A numerical Analysis Tutorial (requires java for simulations):<a href=" http://math.uh.edu/~caboussat/Java/NumericalAnalysis/english/support/"> http://math.uh.edu/~caboussat/Java/NumericalAnalysis/english/support/</a></li>
</ul>
<h2>Intro ML</h2>
<ul>
<li>Edinburgh&#8217;s Introductory Applied Machine Learning Course&#8217;s Video &#8211; <a href="http://groups.inf.ed.ac.uk/vision/VIDEO/2010/iaml.htm">http://groups.inf.ed.ac.uk/vision/VIDEO/2010/iaml.htm</a></li>
<li>Stanford OpenClassRoom Machine learning &#8211; Andrew Ng&#8217;s course- <a href="http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=MachineLearning">http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=MachineLearning</a></li>
<li>Edinburgh Uni&#8217;s Learning from Data Lecture Notes &#8211; <a href="http://www.inf.ed.ac.uk/teaching/courses/lfd/lfdlectures.html">http://www.inf.ed.ac.uk/teaching/courses/lfd/lfdlectures.html</a></li>
</ul>
<h2>Matlab</h2>
<ul>
<li>Introductory Matlab Notes &#8211; <a href="http://www.inf.ed.ac.uk/teaching/courses/lfd/matlab2005.pdf">http://www.inf.ed.ac.uk/teaching/courses/lfd/matlab2005.pdf</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/1198/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic Concepts in Functional Programming Part 1</title>
		<link>http://www.codedanger.com/caglar/archives/999?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-concepts-in-functional-programming-part-1</link>
		<comments>http://www.codedanger.com/caglar/archives/999#comments</comments>
		<pubDate>Mon, 19 Sep 2011 18:30:21 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[bound variables]]></category>
		<category><![CDATA[first class function]]></category>
		<category><![CDATA[free variables]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[higher order functions]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=999</guid>
		<description><![CDATA[In a series of posts I&#8217;ll try to summarize (only briefly) the basic concepts of functional programming. Functional Programming According to wikipedia the definition of functional programming is: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the [...]]]></description>
			<content:encoded><![CDATA[<p><br />
In a series of posts I&#8217;ll try to summarize (only briefly) the basic concepts of functional programming.</p>
<h2>Functional Programming</h2>
<p>According to wikipedia the definition of functional programming is:</p>
<blockquote><p>In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.[1] Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.</p></blockquote>
<p>Functional programming is a style of programming which models computations as the evaluation of expressions and in functional programming the main essence of the programs is functions not objects or procedures. Functional programming requires that those functions to be first order <del>functions </del> entities. Which means that those functions can be passed as an argument or manipulated like any other value in the program and it is possible to define another function within a function. There is an important feature of pure functional languages:</p>
<h3>Referential Transparency</h3>
<p>Referential Transparency means given a function and input, you&#8217;ll always get the same output when you pass that input to the function. There is no external state that is used in that function. Hence referential transparent function depends only on its input. For example:</p>

<div class="wp_codebox"><table><tr id="p9997"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p999code7"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> doubleX<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> x<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> x<span style="color: #339933;">*</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In a pure functional language, all functions are referentially transparent(pure). The counter example (referential opaqueness) of that might be:</p>

<div class="wp_codebox"><table><tr id="p9998"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p999code8"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> M<span style="color: #339933;">=</span><span style="color: #0000dd;">12</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> getX<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> x<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> x<span style="color: #339933;">*</span>M<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Exercise to the reader: Are mathematical functions referential transparent?</p>
<h3>Resources</h3>
<p>What does functional programming mean?: <a href="http://dl.dropbox.com/u/7810909/docs/what-does-fp-mean/what-does-fp-mean/html/index.html">http://dl.dropbox.com/u/7810909/docs/what-does-fp-mean/what-does-fp-mean/html/index.html</a><br />
HaskellWiki, Functional Programming: <a href="http://www.haskell.org/haskellwiki/Functional_programming" target="_blank">http://www.haskell.org/haskellwiki/Functional_programming</a><br />
C2, Functional Programming <a href="http://c2.com/cgi/wiki?FunctionalProgramming" target="_blank">http://c2.com/cgi/wiki?FunctionalProgramming</a><br />
Stackoverflow, What is Referential Transparency? <a href="http://stackoverflow.com/questions/210835/what-is-referential-transparency" target="_blank">http://stackoverflow.com/questions/210835/what-is-referential-transparency</a></p>
<h2>First class Functions</h2>
<p>A programming language is said to have a first class function if it treats functions as a first class object. Which implies that it should satisfy the following conditions without recursively invoking a compiler or interpreter or otherwise metaprogramming:</p>
<ul>
<li>Create new functions from preexisting functions at run-time</li>
<li>Store functions in collections</li>
<li>Use functions as arguments to other functions</li>
<li>Use functions as return values of other functions</li>
</ul>
<p>For example javascript and python supports first class functions. An example on this:</p>

<div class="wp_codebox"><table><tr id="p9999"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p999code9"><pre class="javascript" style="font-family:monospace;">var compose = function (f, g) {
    return function (x) {
        return f(g(x));
    };
};
&nbsp;
var fn  = [Math.sin,  Math.cos,  function (x) { return Math.pow(x, 3);   }];
var inv = [Math.asin, Math.acos, function (x) { return Math.pow(x, 1/3); }];
&nbsp;
(function () {
    for (var i = 0; i &amp;lt; 3; i++) {
        var f = compose(inv[i], fn[i]);
        print(f(0.5));    // 0.5
    }
})();</pre></td></tr></table></div>

<p>&nbsp;</p>
<h3>Resources:</h3>
<p>Wikipedia, First class Functions: <a href="http://en.wikipedia.org/wiki/Free_variables_and_bound_variables">http://en.wikipedia.org/wiki/First-class_function</a><br />
Rosetta Code, First class Functions: http://rosettacode.org/wiki/First-class_functions#JavaScript</p>
<h2>Higher Order Functions</h2>
<p>Higher-order functions are functions which take one or more functions as an input or return/output a function. It is pretty straightforward to implement them in Python:</p>

<div class="wp_codebox"><table><tr id="p99910"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p999code10"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> f<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
	    <span style="color: #ff7700;font-weight:bold;">def</span> g<span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>:
	        <span style="color: #ff7700;font-weight:bold;">return</span> x + n
	    <span style="color: #ff7700;font-weight:bold;">return</span> g</pre></td></tr></table></div>

<p>In C you can use function pointers to accomplish this:</p>

<div class="wp_codebox"><table><tr id="p99911"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p999code11"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Resource of this code is Wikipedia: http://en.wikipedia.org/wiki/Higher-order_function</span>
<span style="color: #666666; font-style: italic;">//Compute the integral of f() within the interval [a,b]</span>
<span style="color: #993333;">double</span> integral<span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>f<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">double</span> x<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #993333;">double</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">double</span> b<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">double</span>  sum<span style="color: #339933;">,</span> dt<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span>     i<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Numerical integration: 0th order approximation</span>
    sum <span style="color: #339933;">=</span> <span style="color:#800080;">0.0</span><span style="color: #339933;">;</span>
    dt <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>b <span style="color: #339933;">-</span> a<span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color:#800080;">100.0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>  i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #0000dd;">100</span><span style="color: #339933;">;</span>  i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        sum <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>f<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">/</span><span style="color:#800080;">100.0</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>b <span style="color: #339933;">-</span> a<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> a<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> dt<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> sum<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In many programming languages, map a higher-order function that applies a given function to each element of a list, returning a list of results. An example in perl is:</p>

<div class="wp_codebox"><table><tr id="p99912"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p999code12"><pre class="perl" style="font-family:monospace;">  <span style="color: #666666; font-style: italic;">#For example map in the following example translates a list of numbers to their squared values.</span>
  <span style="color: #b1b100;">my</span> <span style="color: #0000ff;">@squares</span> <span style="color: #339933;">=</span> <a href="http://perldoc.perl.org/functions/map.html"><span style="color: #000066;">map</span></a> <span style="color: #009900;">&#123;</span> <span style="color: #0000ff;">$_</span> <span style="color: #0000ff;">&amp;gt</span><span style="color: #339933;">;</span> <span style="color: #cc66cc;">5</span> <span style="color: #339933;">?</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">$_</span> <span style="color: #339933;">*</span> <span style="color: #0000ff;">$_</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span> <span style="color: #0000ff;">@numbers</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Resources</h3>
<p>Wikipedia, Higher Order Functions: <a href="http://en.wikipedia.org/wiki/Higher-order_function">http://en.wikipedia.org/wiki/Higher-order_function</a><br />
c2, Higher Order Functions <a href="http://c2.com/cgi/wiki?HigherOrderFunction" target="_blank">http://c2.com/cgi/wiki?HigherOrderFunction</a></p>
<h2>Free and Bound Variables</h2>
<p>&nbsp;</p>
<p>According to SICP the definition of free and bound variables are,</p>
<p>A bound variable:</p>
<blockquote><p>A variable, V, is “bound in an expression”, E, if the meaning of E is unchanged by the uniform replacement of a variable, W, not occurring in E, for every occurrence of V in E.</p></blockquote>
<p>And a free variable is,</p>
<blockquote><p>A variable, V, is “free in an expression”, E, if the meaning of E is changed by the uniform of replacement of a variable, W, not occurring in E, for every occurrence of V in E.</p></blockquote>
<p>In first order logic, a variable is said to occur free in a formula X if and only if it is not within the &#8220;scope&#8221; of a quantifier (existential or universal).</p>
<p>Basically a free variable is a notation that specifies places in an expression where substitution may take place.<br />
Each of the variable binding operators below, binds the variable x. Hence x becomes a bound variable:<br />
<img src="data:image/png;base64,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" alt="" /></p>
<p>Free and Bound variables, Wikipedia: <a href="http://en.wikipedia.org/wiki/Free_variables_and_bound_variables">http://en.wikipedia.org/wiki/Free_variables_and_bound_variables</a></p>
<p>Free and Bound Variables, Saarland: <a title="Free and Bound Variables" href="http://www.coli.uni-saarland.de/projects/milca/esslli/html/node8.html" target="_blank">http://www.coli.uni-saarland.de/projects/milca/esslli/html/node8.html</a></p>
<p>First-Order Logic: bound variables, free variables <a href="http://cnx.org/content/m12081/latest/" target="_blank">http://cnx.org/content/m12081/latest/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/999/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Philosophy and Computer Science</title>
		<link>http://www.codedanger.com/caglar/archives/1134?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=philosophy-and-computer-science</link>
		<comments>http://www.codedanger.com/caglar/archives/1134#comments</comments>
		<pubDate>Wed, 07 Sep 2011 20:12:54 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Philosophy]]></category>
		<category><![CDATA[complexity]]></category>
		<category><![CDATA[digital philosophy]]></category>
		<category><![CDATA[philosophy of computer science]]></category>
		<category><![CDATA[theoretical computer science]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=1134</guid>
		<description><![CDATA[I&#8217;ve just found out an interesting MIT course on Philosophy and Theoretical Computer Science with code 6.893 and thought by Scott Aaronson. The most attractive part of this course for me was articles included in the reading list of the web page. There are great articles in that list: Scott Aaronson, NP-complete Problems and Physical Reality [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just found out an interesting MIT course on <a href="http://stellar.mit.edu/S/course/6/fa11/6.893/index.html">Philosophy and Theoretical Computer Science</a> with code 6.893 and thought by Scott Aaronson. The most attractive part of this course for me was articles included in the reading list of the web page. There are great articles in that list:</p>
<p>Scott Aaronson, <a href="http://www.scottaaronson.com/papers/npcomplete.pdf">NP-complete Problems and Physical Reality</a><br />
Scott Aaronson, <a href="http://www.scottaaronson.com/papers/pnp.pdf">Is P Versus NP Formally Independent?</a><br />
Scott Aaronson and John Watrous, <a href="http://www.scottaaronson.com/papers/ctc.pdf">Closed Timelike Curves Make Quantum and Classical Computing Equivalent</a><br />
Ethan Bernstein and Umesh Vazirani, <a href="http://www.cs.berkeley.edu/~vazirani/pubs/bv.ps">Quantum Complexity Theory</a><br />
Nick Bostrom, <a href="http://www.simulation-argument.com/simulation.html">Are You Living In A Computer Simulation?</a><br />
David Chalmers, <a href="http://consc.net/papers/rock.html">Does A Rock Implement Every Finite-State Automaton?</a><br />
David Deutsch, <a href="http://www.hpc.unm.edu/~alsing/Courses/RQI/articles/deutsch_prd44_p3197_Y91_qm_closed_timelike_curves.pdf">Quantum Mechanics Near Closed Timelike Lines</a><br />
David Deutsch, <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.41.2382&amp;rep=rep1&amp;type=pdf">Quantum theory, the Church-Turing Principle and the universal quantum computer</a><br />
Jack Edmonds, <a href="http://www.stanford.edu/class/cme305/References/pathstrees.pdf">Paths, Trees, and Flowers</a> (Section 2)<br />
Hector Levesque, <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.150.1333&amp;rep=rep1&amp;type=pdf">Is It Enough To Get The Behaviour Right?</a><br />
Christos Papadimitriou, <a href="http://www.cs.berkeley.edu/~christos/stoc01.ps.ps">Algorithms, Games, and the Internet</a><br />
Ian Parberry, <a href="http://larc.unt.edu/ian/pubs/knowledge.pdf">Knowledge, Understanding, and Computational Complexity</a><br />
Juergen Schmidhuber, <a href="ftp://ftp.idsia.ch/pub/juergen/everything.pdf">A Computer Scientist&#8217;s View of Life, the Universe, and Everything</a><br />
Stuart Shieber, <a href="http://www.eecs.harvard.edu/shieber/Biblio/Papers/turing-interactive-proof.pdf">The Turing Test As Interactive Proof</a><br />
Michael Sipser, <a href="http://www.eecs.berkeley.edu/~luca/cs172-04/sipser92history.pdf">The History and Status of the P versus NP Question</a><br />
Robert Stalnaker, <a href="http://web.cs.gc.cuny.edu/~kgb/course/stalnaker2.pdf">The Problem of Logical Omniscience I</a><br />
Alan Turing, <a href="http://www.thocp.net/biographies/papers/turing_oncomputablenumbers_1936.pdf">On Computable Numbers, With An Application to the Entscheidungsproblem</a><br />
Alan Turing, <a href="http://www.loebner.net/Prizef/TuringArticle.html">Computing Machinery and Intelligence</a><br />
Leslie Valiant, <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.94.6289&amp;rep=rep1&amp;type=pdf">A Theory of the Learnable<br />
</a>Leslie Valiant, <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=1&amp;sqi=2&amp;ved=0CBUQFjAA&amp;url=http%3A%2F%2Fpeople.seas.harvard.edu%2F~valiant%2Fevolvability-2008.pdf&amp;rct=j&amp;q=valiant%20evolvability&amp;ei=0_0_TvbYEcPk0QH2zbjFBw&amp;usg=AFQjCNEhdp_U7HgVQxME-t_-M_Pn15S9JQ&amp;cad=rja">Evolvability</a><br />
Avi Wigderson, <a href="http://www.math.ias.edu/~avi/PUBLICATIONS/MYPAPERS/W06/w06.pdf">P, NP, and Mathematics &#8211; A Computational Complexity Perspective</a><br />
Avi Wigderson, <a href="http://www.math.ias.edu/~avi/PUBLICATIONS/MYPAPERS/AW09/AW09.ps">Knowledge, Creativity, and P versus NP</a><br />
Ronald de Wolf, <a href="http://homepages.cwi.nl/~rdewolf/publ/philosophy/phthesis.pdf">Philosophical Applications of Computational Learning Theory</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/1134/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bitwise Operators and Binary Tricks for System Programming</title>
		<link>http://www.codedanger.com/caglar/archives/1058?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bitwise-operators-and-tricks-for-programming</link>
		<comments>http://www.codedanger.com/caglar/archives/1058#comments</comments>
		<pubDate>Wed, 07 Sep 2011 11:48:06 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Engineering]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[binary operators]]></category>
		<category><![CDATA[bitwise]]></category>
		<category><![CDATA[bitwise operations]]></category>
		<category><![CDATA[low level programming]]></category>
		<category><![CDATA[system programming]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=1058</guid>
		<description><![CDATA[Bitwise operators in most of the programming languages are common and inherited from the C (e.g.: &#038;, &#124;, ^, >>, &#8230;). These operations are critical in the low-level programming (for instance for writing drivers). In the beginning of this post I&#8217;ll just briefly pass over them and present some tricks using them. As a programming [...]]]></description>
			<content:encoded><![CDATA[<p>Bitwise operators in most of the programming languages are common and inherited from the C (e.g.: &#038;, |, ^, >>, &#8230;). These operations are critical in the low-level programming (for instance for writing drivers).</p>
<p>In the beginning of this post I&#8217;ll just briefly pass over them and present some tricks using them. As a programming language choice, I&#8217;ll give examples from C and python.</p>
<p>See the resources for more complete and detailed overview.</p>
<h3></h3>
<h3>Two most Fundamental Bitwise operators</h3>
<p>There are two types of conditional operator in most of the programming languages, logical one the bitwise one. For example &#8220;bitwise AND&#8221; is shown as &#8220;&#038;&#8221; and the &#8220;logical AND&#8221; is shown with &#8220;&#038;&#038;&#8221;. Similarly &#8220;bitwise OR&#8221; is | and &#8220;logical OR&#8221; is &#8220;||&#8221;.</p>
<h4><strong></strong>AND operator</h4>
<p>Bitwise AND (&#038;) is very similar to the &#8220;logical AND&#8221; but instead it works with bits only. The bitwise AND compares each bit of the first operand to the corresponding bit of the second operand. It returns 1 if and only if both of its operands are equal to 1, otherwise it returns 0.</p>
<p>For example 00&#038;11 is 0.</p>
<p>Let&#8217;s fire up python shell and write 5&#038;7 the result is 5 but how?</p>
<p>5 in binary format is 0101 and 7 is 0111 and by comparing each bit we&#8217;ll get 0101 which is 5.</p>
<p>We can use this notion for detecting if a bit is 0 or 1. </p>
<p>For example, given a bit pattern: 0011 (decimal 3), we can determine whether the second bit is 1 may be done by using a bitwise AND with a bit pattern containing 1 only in that bit:<br />
<code><br />
     0011 (decimal 3)<br />
&#038;   0010 (decimal 2)<br />
--------------------<br />
  = 0010 (decimal 2)<br />
</code><br />
Because the result 0010 is non-zero, we know the second bit in the original pattern was 1. This process is usually called as bit masking. </p>
<h4>OR operator</h4>
<p>A bitwise OR (|) takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of corresponding bits. For each pair, if either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.</p>
<p>For example if calculate 5&#038;7 in python you&#8217;ll get 7. Because 5 in binary format is 0101 and 7 is 0111 and by comparing each bit with inclusive OR we&#8217;ll get 0111 which is 7.</p>
<p>The bitwise OR may be used to set selected bits. One example is to set a specific bit (or flag) in a register where each bit represents an individual Boolean state. For example: 0010 (decimal 2) can be considered a set of four flags. The first, second, and fourth flags are clear (0), while the third flag is set (1). The first flag may be set by performing a bitwise OR between this value and a bit pattern in which the first flag is set:<br />
<code><br />
   0010 (decimal 2 )<br />
|  1000 (decimal 8 )<br />
--------------------<br />
 = 1010 (decimal 10 )<br />
</code></p>
<p>This technique is an efficient way to deal with a number of Boolean values using the minimum of memory.</p>
<h3><strong>Other important bitwise operators</strong></h3>
<h4>NOT</h4>
<p>The bitwise NOT (~), or complement, is a unary operation that performs logical negation on each bit, forming the ones&#8217; complement of the given binary value. Digits which were 0 become 1, and vice versa. For example:</p>
<p>~7 is 8. Because 7 in binary format is 0111 and by converting each bit we&#8217;ll get 1000 which is 8. </p>
<p>If the number is signed we&#8217;ll use two&#8217;s complement for the bitwise not operator.</p>
<h4>XOR</h4>
<p>The term bitwise XOR (^) stands for &#8220;exclusive OR,&#8221; and means &#8220;one or the other, but not both.&#8221; In other words, XOR compares each bit, returns 1 if and only if exactly one of its operands is 1. If both operands are 0, or both are 1, then XOR returns 0. For example:<br />
<code><br />
     0101 (decimal 5)<br />
^   0011 (decimal 3)<br />
--------------------<br />
  = 0110 (decimal 6)<br />
</code><br />
Assembly language programmers sometimes use the XOR operation as a short-cut to set the value of a register to zero. Performing XOR on a value against itself always yields zero, and on many architectures this operation requires fewer CPU clock cycles and/or fewer bytes (less precious cache-space) than loading a zero value and saving it to the register.</p>
<p>The bitwise XOR may be used to invert selected bits in a register (also called toggle or flip). Given the bit pattern: 0010 (decimal 2) the first and third bits may be toggled simultaneously by a bitwise XOR with a bit pattern containing 1 in the first and third positions:<br />
<code><br />
    0010 (decimal 2 )<br />
^   1010 (decimal 10 )<br />
---------------------<br />
  = 1000 (decimal 8 )<br />
</code><br />
This technique also may be used to manipulate bit patterns representing sets of Boolean states.</p>
<h3><strong>Bitwise shifts</strong></h3>
<p>There are two bitwise shift operators and they are shift left and shift right. In C, these are represented by the << and >> operators, respectively. These operations are very simple, and do exactly what they say: shift bits to the left or to the right. The syntax for a shift operation is as follows:<br />
<code><br />
[integer] [operator] [number of places]<br />
</code><br />
A statement of this form shifts the bits in [integer] by the number of places indicated, in the direction specified by the operator. </p>
<h4>Left Shift</h4>
<p>Left shift basically shifts the binary n bits to the left. A left arithmetic shift by n is equivalent to multiplying by 2^n (provided the value does not overflow). For example:</p>
<p>Fire up your python shell and run the following in the shell:<br />
<code><br />
3 << 2<br />
</code><br />
Result of this operation is 12. Because,</p>
<p>Decimal 3 is 0011 in binary. When you shift 0011 2 bits to the left, you'll get 1100 and that's 12.  </p>
<p>Another example is:<br />
<code><br />
x = 0000 1010 1000 0001;<br />
x = x << 4;<br />
</code><br />
After shifting 4 bits, the new x will be:<br />
<code><br />
1010 1000 0001 0000<br />
</code><br />
Every bit is shifted to the left by one place. When you do this, the MSB (most significant bit, remember?) of x is lost, because there isn't another place to shift it to. Similarly, after a shift left, the LSB of x will always be 0. There is no position to the right of the LSB, and so there's nothing to shift into the LSB, so it's assigned a value of 0.</p>
<h4>Right Shift</h4>
<p>Similar to the left shift, right shift basically shifts the binary number n bits to the left. That's actually taking two's complement of the number or dividing by 2^n. An example is:<br />
<code><br />
12>>2<br />
</code><br />
and result of this is 3. Because 12 in binary is 1100 and when you shift two bits you'll get 0011 which is 3.</p>
<p>Another example is,<br />
<code><br />
x = 0110 1111 1001 0001;<br />
x = x >> 4;<br />
</code><br />
and the x in the end will be 0000 0110 1111 1001. Here, the bits are being shifted right by four places.</p>
<h3>Some Hacks</h3>
<h4><strong>Computing the modulus:</strong></h4>
<p>If the divisor is a power of 2, the modulo (%) operation can be done with:<br />
modulus = numerator &#038; (divisor - 1);<br />
This is about 600% faster.<br />
<code><br />
x = 131 % 4;<br />
//equals:<br />
x = 131 &#038; (4 - 1);<br />
</code></p>
<h4><strong>Absolute Value</strong></h4>
<p>Forget Math.abs() for time critical code. Version 1 is 2500% faster than Math.abs(), and the funky bitwise version 2 is again 20% faster than version 1.<br />
<code><br />
//version 1<br />
i = x < 0 ? -x : x;</p>
<p>//version 2<br />
i = (x ^ (x >> 31)) - (x >> 31);<br />
</code></p>
<h4><strong>Swap integers without a temporary variable using XOR</strong></h4>
<p>That's a pretty neat trick and this is about 20% faster.<br />
<code><br />
int a, b, t;<br />
a = b;<br />
b = t;</p>
<p>//equals:<br />
a ^= b;<br />
b ^= a;<br />
a ^= b;<br />
</code></p>
<h4><strong>Multiplication</strong></h4>
<p>Here is a bitwise multiplication algorithm only using bitwise shifts and addition.</p>

<div class="wp_codebox"><table><tr id="p105814"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code" id="p1058code14"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> multiply <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">int</span> c <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>b<span style="color: #339933;">!=</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>b <span style="color: #339933;">&amp;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
      c <span style="color: #339933;">=</span> c <span style="color: #339933;">+</span> a<span style="color: #339933;">;</span>
    a <span style="color: #339933;">=</span> a<span style="color: #339933;">&lt;&lt;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    b <span style="color: #339933;">=</span> b<span style="color: #339933;">&gt;&gt;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">return</span> c<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #993333;">int</span> main <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">,</span> b <span style="color: #339933;">=</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">,</span> c<span style="color: #339933;">,</span> d<span style="color: #339933;">;</span>
  c <span style="color: #339933;">=</span> multiply<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  d <span style="color: #339933;">=</span> a <span style="color: #339933;">*</span> b<span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>c <span style="color: #339933;">==</span> d<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Result is %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Incorrect : %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h4><strong>Detect if two integers have opposite signs</strong></h4>
<div>
<code><br />
int x, y;               // input values to compare signs<br />
bool f = ((x ^ y) < 0); // true iff x and y have opposite signs<br />
</code></p>
<h4>Check if an integer is even/uneven using bitwise AND</h4>
<p><code><br />
  isEven = (x &#038; 1) ^ ((-1 &#038; 1) | ((x < 0) ? 0 : 1)));<br />
</code></p>
<p>This example is taken from <a href="http://stackoverflow.com/questions/160930/how-do-i-check-if-an-integer-is-even-or-odd" target="_blank">this SO post</a>.
</div>
<h4><strong>Compute the minimum (min) or maximum (max) of two integers without branching</strong></h4>
<p>This one is from <a title="Bit Twiddling Hacks" href="http://graphics.stanford.edu/~seander/bithacks.html" target="_blank">Bit Twiddling Hacks</a> page:</p>
<blockquote><p>
If you know that INT_MIN <= x - y <= INT_MAX, then you can use the following, which are faster because (x - y) only needs to be evaluated once.<br />
<code><br />
r = y + ((x - y) &#038; ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y)<br />
r = x - ((x - y) &#038; ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)<br />
</code><br />
Note that the 1989 ANSI C specification doesn't specify the result of signed right-shift, so these aren't portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a signed operand to produce all one bits when negative, so cast to signed there.
</p></blockquote>
<h4><strong>Sign Flipping</strong></h4>
<p>Sign flipping using NOT or XOR:<br />
<code><br />
i = -i;<br />
//equals<br />
i = ~i + 1;<br />
//or<br />
i = (i ^ -1) + 1;<br />
</code></p>
<h3><strong>Useful Resources</strong></h3>
<p><a title="Bitwise Tricks" href="http://resnet.uoregon.edu/~gurney_j/jmpc/bitwise.html" target="_blank">Bitwise Tricks</a></p>
<p><a title="Bitwise Operations in C" href="http://www.gamedev.net/page/resources/_/reference/programming/bitwise-operations-in-c-r1563" target="_blank">Bitwise Operations in C</a></p>
<p><a title="The art of Programming Fasc 1" href="http://www-cs-faculty.stanford.edu/~uno/fasc1a.ps.gz" target="_blank">The art of Programming Fasc 1</a></p>
<p><a title="Bitwise gems – fast integer math" href="http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/" target="_blank">Bitwise gems – fast integer math</a></p>
<p><a title="Bit Twiddling Hacks" href="http://graphics.stanford.edu/~seander/bithacks.html" target="_blank">Bit Twiddling Hacks</a></p>
<p><a title="Bitwise Operations" href="http://en.wikipedia.org/wiki/Bitwise_operation" target="_blank">Bitwise Operations</a></p>
<p><a title="Reciprocal Multiplication, a tutorial" href="http://www.cs.uiowa.edu/~jones/bcd/divide.html" target="_blank">Reciprocal Multiplication, a tutorial</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/1058/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP IPv6 address to Decimal Format Conversion</title>
		<link>http://www.codedanger.com/caglar/archives/1039?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-ipv6-address-to-decimal-conversion</link>
		<comments>http://www.codedanger.com/caglar/archives/1039#comments</comments>
		<pubDate>Mon, 27 Jun 2011 07:15:18 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Network Engineering]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[ip]]></category>
		<category><![CDATA[ip to decimal]]></category>
		<category><![CDATA[ip to long]]></category>
		<category><![CDATA[ipv6]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=1039</guid>
		<description><![CDATA[Storing IP addresses in database as decimal have several advantages on storing as a string (storing, efficiency, processing&#8230; etc). But my goal was to be able to easily query if an IP address is in a block or between a given IP range. The following two functions are often handy for converting a string IPV6 [...]]]></description>
			<content:encoded><![CDATA[<p>Storing IP addresses in database as decimal have several advantages on storing as a string (storing, efficiency, processing&#8230; etc). But my goal was to be able to easily query if an IP address is in a block or between a given IP range. The following two functions are often handy for converting a string IPV6 address to long decimal format. These functions require php gmp to be able to generate long decimals.</p>

<div class="wp_codebox"><table><tr id="p103916"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="code" id="p1039code16"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">function</span> ip2long6<span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$ip_n</span> <span style="color: #339933;">=</span> inet_pton<span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$bits</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">15</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// 16 x 8 bit = 128bit</span>
    <span style="color: #000088;">$ipv6long</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$bits</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$bin</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/sprintf"><span style="color: #990000;">sprintf</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%08b</span>&quot;</span><span style="color: #339933;">,</span><span style="color: #009900;">&#40;</span><a href="http://www.php.net/ord"><span style="color: #990000;">ord</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ip_n</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$bits</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6long</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$ipv6long</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$bin</span><span style="color: #339933;">.</span><span style="color: #000088;">$ipv6long</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$ipv6long</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$bin</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000088;">$bits</span><span style="color: #339933;">--;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> <a href="http://www.php.net/gmp_strval"><span style="color: #990000;">gmp_strval</span></a><span style="color: #009900;">&#40;</span><a href="http://www.php.net/gmp_init"><span style="color: #990000;">gmp_init</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6long</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> long2ip6<span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6long</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$bin</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/gmp_strval"><span style="color: #990000;">gmp_strval</span></a><span style="color: #009900;">&#40;</span><a href="http://www.php.net/gmp_init"><span style="color: #990000;">gmp_init</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6long</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><a href="http://www.php.net/strlen"><span style="color: #990000;">strlen</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bin</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">128</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$pad</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">128</span> <span style="color: #339933;">-</span> <a href="http://www.php.net/strlen"><span style="color: #990000;">strlen</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bin</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;=</span> <span style="color: #000088;">$pad</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$bin</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;0&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$bin</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000088;">$bits</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$ipv6</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$bits</span> <span style="color: #339933;">&lt;=</span> <span style="color: #cc66cc;">7</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$bin_part</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/substr"><span style="color: #990000;">substr</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bin</span><span style="color: #339933;">,</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bits</span><span style="color: #339933;">*</span><span style="color: #cc66cc;">16</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">16</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$ipv6</span> <span style="color: #339933;">.=</span> <a href="http://www.php.net/dechex"><span style="color: #990000;">dechex</span></a><span style="color: #009900;">&#40;</span><a href="http://www.php.net/bindec"><span style="color: #990000;">bindec</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bin_part</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$ipv6</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/dechex"><span style="color: #990000;">dechex</span></a><span style="color: #009900;">&#40;</span><a href="http://www.php.net/bindec"><span style="color: #990000;">bindec</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$bin_part</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000088;">$bits</span><span style="color: #339933;">++;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> inet_ntop<span style="color: #009900;">&#40;</span>inet_pton<span style="color: #009900;">&#40;</span><a href="http://www.php.net/substr"><span style="color: #990000;">substr</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$ipv6</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;fe80:0:0:0:202:b3ff:fe1e:8329&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #000088;">$ipv6long</span> <span style="color: #339933;">=</span>  ip2long6<span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #000088;">$ipv6</span> <span style="color: #339933;">=</span> long2ip6<span style="color: #009900;">&#40;</span><span style="color: #000088;">$ipv6long</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/1039/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Traverse Files In the Source Folder for C++ Lint</title>
		<link>http://www.codedanger.com/caglar/archives/1021?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=traverse-files-in-the-source-folder-for-c-lint</link>
		<comments>http://www.codedanger.com/caglar/archives/1021#comments</comments>
		<pubDate>Tue, 21 Jun 2011 06:43:30 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Systems]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[coding style]]></category>
		<category><![CDATA[cpplint]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[traverse]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=1021</guid>
		<description><![CDATA[Google has an awesome C++ coding style guideline and they have done a very good job on creating a very handy C++ lint based on that guideline. I have downloaded it renamed that script to cpplint, chmod to executable and move to /usr/bin to use. (Also changed the shebang to /us/bin/env python, because default shebang [...]]]></description>
			<content:encoded><![CDATA[<p>Google has an awesome<a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml"> C++ coding style guideline</a> and they have done a very good job on creating a very handy <a href="http://google-styleguide.googlecode.com/svn-history/r15/trunk/cpplint/cpplint.py">C++ lint</a> based on that guideline.</p>
<p>I have downloaded it renamed that script to cpplint, chmod to executable and move to /usr/bin to use. (Also changed the shebang to /us/bin/env python, because default shebang uses the python2.4)</p>
<p>But this script solely itself can not traverse the files in a folder recursively and output the errors to a file, hence I had to write a basic bash script by myself:</p>

<div class="wp_codebox"><table><tr id="p102118"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p1021code18"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;$2&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
  <span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #007800;">$2</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-d</span> <span style="color: #ff0000;">&quot;$1&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
    <span style="color: #c20cb9; font-weight: bold;">find</span> <span style="color: #007800;">$1</span> <span style="color: #660033;">-type</span> f <span style="color: #660033;">-iname</span> \<span style="color: #000000; font-weight: bold;">*</span>.cc <span style="color: #660033;">-or</span> <span style="color: #660033;">-iname</span> \<span style="color: #000000; font-weight: bold;">*</span>.h <span style="color: #660033;">-exec</span> <span style="color: #c20cb9; font-weight: bold;">sh</span> <span style="color: #660033;">-c</span>  <span style="color: #ff0000;">&quot;cpplint --filter=+build,+readability,+runtime,-whitespace --output=vs7 '{}'&quot;</span> \; 
  <span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #000000; font-weight: bold;">else</span> 
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Please enter a log file name to output the errors to and a path for the source folder to traverse for errors: ./check_cpplint [search folder] [log file]&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p>First parameter of this script is the path of the source code&#8217;s folder that your C++ codes are located in and the second one is the file that the errors will be written to.</p>
<p>BTW there is another great c++ lint called <a href="http://sourceforge.net/apps/mediawiki/cppcheck/index.php?title=Main_Page">cppcheck</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/1021/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Learn you a haskell for Math! &#8211; Part 1</title>
		<link>http://www.codedanger.com/caglar/archives/959?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=learn-you-a-haskell-for-math-part-1</link>
		<comments>http://www.codedanger.com/caglar/archives/959#comments</comments>
		<pubDate>Sun, 12 Jun 2011 22:28:03 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Softwares]]></category>
		<category><![CDATA[calculus]]></category>
		<category><![CDATA[derivation]]></category>
		<category><![CDATA[derivative]]></category>
		<category><![CDATA[function approximation]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[integral]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[riemann sum]]></category>
		<category><![CDATA[trapezoidal rule]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=959</guid>
		<description><![CDATA[It has been for some time since I&#8217;ve used haskell for programming (in fact for my personal and work related projects I don&#8217;t use haskell. because I still feel so novice at it), so I thought that implementing some basic mathematical functions might be a good exercise. I&#8217;m planning to write 3 series, in the [...]]]></description>
			<content:encoded><![CDATA[
<p>It has been for some time since I&#8217;ve used haskell for programming (in fact for my personal and work related projects I don&#8217;t use haskell. because I still feel so novice at it), so I thought that implementing some basic mathematical functions might be a good exercise. I&#8217;m planning to write 3 series, in the first part I&#8217;ll implement some of the basic calculus operators such as integration and derivative of a function. In the second part I&#8217;ll implement a few numerical analysis algorithms like newton-raphson, taylor series approximation and sieve of aristothenes. In the third and the last part I&#8217;ll present you the implementation of MCMC and gaussian processes.</p>
<p>If you are using haskell there are too many ways to accomplish a task. As a layman haskell-er, my approaches might be naive.</p>
<p>To find integration and derivation of a function you can use any of the following two different approaches:</p>
<ol>
<li> You can approach problem by using an approximation technique.</li>
<li> You can solve  by symbolically. Implementation of a symbolic solver is harder.</li>
</ol>
<h3>Integral of a Function</h3>
<p>We&#8217;ll try to find the definite integral of a function between upper and lower values, it is basically the area under the curve:</p>
<p><img class="aligncenter" title="Integral Area" src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/90/Integral_as_region_under_curve.png/300px-Integral_as_region_under_curve.png" alt="" width="300" height="263" /></p>
<h4>Riemann Sum Approach</h4>
<p>First approach that I&#8217;ll use will be <a title="Riemann Sum" href="http://en.wikipedia.org/wiki/Riemann_sum">riemann sum</a> is a method for approximating the total area underneath a curve on a graph, otherwise known as an integral of a specific function.</p>
<p>Formal definition (<a title="Riemann Sum" href="http://mathworld.wolfram.com/RiemannSum.html">From Wolfram Math</a>):</p>
<p>Let a <a href="http://mathworld.wolfram.com/ClosedInterval.html">closed interval</a> <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline1.gif" border="0" alt="[a,b]" width="32" height="14" /> be partitioned by points <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline2.gif" border="0" alt="a&lt;x_1&lt;x_2&lt;...&lt;x_(n-1)&lt;b" width="153" height="16" />, where the lengths of the resulting intervals between the points are denoted <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline3.gif" border="0" alt="Deltax_1" width="25" height="14" />, <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline4.gif" border="0" alt="Deltax_2" width="25" height="14" />, &#8230;, <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline5.gif" border="0" alt="Deltax_n" width="25" height="16" />. Let <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline6.gif" border="0" alt="x_k^*" width="13" height="17" /> be an arbitrary point in the <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline7.gif" border="0" alt="k" width="6" height="14" />th subinterval. Then the quantity</p>
<div>
<table cellspacing="0" cellpadding="0" width="100%" align="center">
<tbody>
<tr>
<td align="left"><img src="http://mathworld.wolfram.com/images/equations/RiemannSum/NumberedEquation1.gif" border="0" alt=" sum_(k=1)^nf(x_k^*)Deltax_k " width="80" height="46" /></td>
</tr>
</tbody>
</table>
</div>
<p>is called a Riemann sum for a given function <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline8.gif" border="0" alt="f(x)" width="26" height="14" /> and partition, and the value <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline9.gif" border="0" alt="maxDeltax_k" width="52" height="16" /> is called the <a href="http://mathworld.wolfram.com/MeshSize.html">mesh size</a> of the partition.</p>
<p>If the <a href="http://mathworld.wolfram.com/Limit.html">limit</a> of the Riemann sums exists as <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline10.gif" border="0" alt="maxDeltax_k-&gt;0" width="77" height="16" />, this limit is known as the Riemann integral of <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline11.gif" border="0" alt="f(x)" width="26" height="14" /> over the interval <img src="http://mathworld.wolfram.com/images/equations/RiemannSum/Inline12.gif" border="0" alt="[a,b]" width="32" height="14" />. The shaded areas in the above plots show the <a href="http://mathworld.wolfram.com/LowerSum.html">lower</a> and <a href="http://mathworld.wolfram.com/UpperSum.html">upper sums</a> for a constant <a href="http://mathworld.wolfram.com/MeshSize.html">mesh size</a>.</p>
<p>A general graphical view of convergence of riemann sum to a function is:</p>
<p><img class="aligncenter" title="Riemann Sum Convergence" src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Riemann_sum_convergence.png/600px-Riemann_sum_convergence.png" alt="" width="600" height="600" /></p>
<p>The haskell code of riemann sum is shown below. I have used tail recursion, to learn about tail recursion in haskell see <a href="http://learnyouahaskell.com/recursion#hello-recursion">this</a>.</p>

<div class="wp_codebox"><table><tr id="p95927"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p959code27"><pre class="haskell" style="font-family:monospace;">epsilon<span style="color: #339933; font-weight: bold;">_</span>dx <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">0.000001</span>
<span style="color: #5d478b; font-style: italic;">-- integrate function from a to b</span>
&nbsp;
integrate f a b <span style="color: #339933; font-weight: bold;">=</span> riemannSum f a b epsilon<span style="color: #339933; font-weight: bold;">_</span>dx <span style="color: red;">0</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">--using a tail recursion</span>
<span style="color: #5d478b; font-style: italic;">--integrate a function f from x to b</span>
&nbsp;
riemannSum f x b dx <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: #339933; font-weight: bold;">=</span>
    <span style="color: #06c; font-weight: bold;">if</span> x <span style="color: #339933; font-weight: bold;">&gt;</span> b
      <span style="color: #06c; font-weight: bold;">then</span>
        <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a>
      <span style="color: #06c; font-weight: bold;">else</span>
        riemannSum f <span style="color: green;">&#40;</span>x <span style="color: #339933; font-weight: bold;">+</span> dx<span style="color: green;">&#41;</span> b dx <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: #339933; font-weight: bold;">+</span> <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">*</span> dx<span style="color: green;">&#41;</span>
&nbsp;
f1 x <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">1</span>
f2 x <span style="color: #339933; font-weight: bold;">=</span> x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span>
f3 x <span style="color: #339933; font-weight: bold;">=</span> x <span style="color: #339933; font-weight: bold;">*</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:exp"><span style="font-weight: bold;">exp</span></a><span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span><span style="color: green;">&#41;</span></pre></td></tr></table></div>

<p>type of the integrate function is:</p>

<div class="wp_codebox"><table><tr id="p95928"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p959code28"><pre class="haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> :t integrate
integrate <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a></pre></td></tr></table></div>

<p>A basic test via ghci:</p>

<div class="wp_codebox"><table><tr id="p95929"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p959code29"><pre class="haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> integrate f2 <span style="color: red;">0</span> <span style="color: red;">1</span>
<span style="color: red;">0.33333283333399866</span></pre></td></tr></table></div>

<p>function f2 is $$f(x) = x^2$$</p>
<p>and the integral we are trying to calculate is:<br />
$$\int^b_a f_2(x) dx = \int^1_0 x^2 dx= 0.33333&#8230;$$</p>
<p>so the real and approximated answers are very close.</p>
<p><strong><a title="Trapezoidal Rule" href="http://en.wikipedia.org/wiki/Trapezoidal_rule" target="_blank">Trapezoidal rule</a></strong> (also known as the <strong>trapezoid rule</strong> or <strong>trapezium rule</strong>) is an approximate technique for calculating the <a title="Integral" href="http://en.wikipedia.org/wiki/Integral">definite integral</a></p>
<dl>
<dd><img src="http://upload.wikimedia.org/math/6/0/9/609b0a4b1c6239bca529bfc6462db380.png" alt=" \int_{a}^{b} f(x)\,dx." /></dd>
</dl>
<p>The trapezoidal rule works by approximating the region under the graph of the function <em>f</em>(<em>x</em>) as a <a title="Trapezoid" href="http://en.wikipedia.org/wiki/Trapezoid">trapezoid</a> and calculating its area. It follows that</p>
<dl>
<dd><img src="http://upload.wikimedia.org/math/d/3/e/d3e0169c31cf40e92224358ab3699c52.png" alt=" \int_{a}^{b} f(x)\, dx \approx (b-a)\frac{f(a) + f(b)}{2}." /></dd>
</dl>
<p>The graphical depiction of the definition above is:</p>
<h4>
<div class="wp-caption aligncenter" style="width: 641px"><img class="   " title="Trapezoidal Rule" src="http://upload.wikimedia.org/wikipedia/commons/d/dd/Trapezoidal_rule_illustration.png" alt="" width="540" height="479" /><p class="wp-caption-text">The function f(x) (in blue) is approximated by a linear function (in red).</p></div>
<p>Rule</h4>
<p>The haskell code for the trapezoidal rule using tail recursion (again):</p>

<div class="wp_codebox"><table><tr id="p95930"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code" id="p959code30"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">--number of steps/resolution taken to find an approximate solution</span>
step<span style="color: #339933; font-weight: bold;">_</span>size <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">100000</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- integrate function from a to b</span>
&nbsp;
integrate f a b <span style="color: #339933; font-weight: bold;">=</span> trapezoidalSum f a b <span style="color: red;">0</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>b<span style="color: #339933; font-weight: bold;">-</span>a<span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">/</span>step<span style="color: #339933; font-weight: bold;">_</span>size<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">--use of a tail recursion</span>
<span style="color: #5d478b; font-style: italic;">--integrate a function f from x to b</span>
&nbsp;
trapezoidalSum f x b <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> delta
    <span style="color: #339933; font-weight: bold;">|</span> x <span style="color: #339933; font-weight: bold;">&gt;</span> b <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a>
    <span style="color: #339933; font-weight: bold;">|</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> <span style="color: #339933; font-weight: bold;">=</span> trapezoidalSum f <span style="color: green;">&#40;</span>x <span style="color: #339933; font-weight: bold;">+</span> delta<span style="color: green;">&#41;</span> b <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: #339933; font-weight: bold;">+</span> delta <span style="color: #339933; font-weight: bold;">*</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">+</span> <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>x <span style="color: #339933; font-weight: bold;">+</span> delta<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">/</span> <span style="color: red;">2</span><span style="color: green;">&#41;</span> delta
&nbsp;
f1 x <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">1</span>
f2 x <span style="color: #339933; font-weight: bold;">=</span> x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span>
f3 x <span style="color: #339933; font-weight: bold;">=</span> x <span style="color: #339933; font-weight: bold;">*</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:exp"><span style="font-weight: bold;">exp</span></a><span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span><span style="color: green;">&#41;</span></pre></td></tr></table></div>

<p>Again type of the integrate function is same as in the riemann sum version:</p>

<div class="wp_codebox"><table><tr id="p95931"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p959code31"><pre class="haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> :t integrate
integrate <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double"><span style="color: #cccc00; font-weight: bold;">Double</span></a></pre></td></tr></table></div>

<p>An example test:</p>

<div class="wp_codebox"><table><tr id="p95932"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p959code32"><pre class="haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> integrate f2 <span style="color: red;">0</span> <span style="color: red;">1</span>
<span style="color: red;">0.33334333344937134</span></pre></td></tr></table></div>

<p>&nbsp;</p>
<h3>Derivative of a Function</h3>
<p>First derivative of function at a certain point is actually the tangent of the function at that certain point. Therefore we can write:</p>
<dl>
<dd><img src="http://upload.wikimedia.org/math/9/6/4/964676a345bceb71c391e66d18085c54.png" alt="m = \frac{\Delta f(x)}{\Delta x} = \frac{f(x+h)-f(x)}{h}." /></dd>
</dl>
<p>This expression is <a title="Isaac Newton" href="http://en.wikipedia.org/wiki/Isaac_Newton">Newton</a>&#8216;s <a title="Difference quotient" href="http://en.wikipedia.org/wiki/Difference_quotient">difference quotient</a>. The derivative is the value of the difference quotient as the secant lines approach the tangent line. Formally, the <strong>derivative</strong> of the function <em>ƒ</em> at <em>a</em> is the <a title="Limit of a function" href="http://en.wikipedia.org/wiki/Limit_of_a_function">limit</a></p>
<dl>
<dd><img src="http://upload.wikimedia.org/math/4/2/c/42cf4f4861ae1266b13104c4115e7b5d.png" alt="f'(a)=\lim_{h\to 0}\frac{f(a+h)-f(a)}{h}" /></dd>
<dd> </dd>
<dd>and we can show that in the graph as follows:</dd>
<dd> </dd>
</dl>
<p style="text-align: center;"><img class="aligncenter" title="Tangent and Derivative" src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Secant-calculus.svg/800px-Secant-calculus.svg.png" alt="" width="576" height="410" /></p>
<p style="text-align: center;">&nbsp;</p>
<p style="text-align: left;">By using currying and higher order functions implementing that derivation is straight-forward:</p>
<p style="text-align: left;">&nbsp;</p>

<div class="wp_codebox"><table><tr id="p95933"><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" id="p959code33"><pre class="haskell" style="font-family:monospace;">diff <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Fractional"><span style="color: #cccc00; font-weight: bold;">Fractional</span></a> a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> a<span style="color: green;">&#41;</span>
diff h f x <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>x <span style="color: #339933; font-weight: bold;">+</span> h<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-</span> f x<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">/</span> h 
&nbsp;
f1 x <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">1</span>
f2 x <span style="color: #339933; font-weight: bold;">=</span> x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span>
f3 x <span style="color: #339933; font-weight: bold;">=</span> x <span style="color: #339933; font-weight: bold;">*</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:exp"><span style="font-weight: bold;">exp</span></a><span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">**</span><span style="color: red;">2</span><span style="color: green;">&#41;</span></pre></td></tr></table></div>

<p>The test result at ghci is:</p>

<div class="wp_codebox"><table><tr id="p95934"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p959code34"><pre class="haskell" style="font-family:monospace;"><span style="color: #339933; font-weight: bold;">*</span>Main<span style="color: #339933; font-weight: bold;">&gt;</span> diff <span style="color: red;">0.00001</span> f2 <span style="color: red;">10</span>
<span style="color: red;">20.00000999942131</span></pre></td></tr></table></div>

<p>we have chosen h as 0.0001 and differentiate function $$f_2(x)$$ at point 10. Derivative of $$f_2(x)$$ is $$f&#8217;_2(x) = 2x$$ and the result at 10 is, $$f&#8217;_2(10) = 20$$ . Result that we have found with the above haskell code is very close to the exact value.</p>
<h3>Further Reading</h3>
<p>&nbsp;</p>
<p><a title="Integral Calculus in Haskell" href="http://iam.elbenshira.com/archives/151_integral-calculus-in-haskell/">Integral Calculus in Haskell</a>, Thoughts</p>
<p><a title="Functional Differentiation" href="http://www.haskell.org/haskellwiki/Functional_differentiation">Functional Differentiation</a>, Haskell.org</p>
<p>&nbsp;</p>
<p>Note: I mistakenly post the wrong revision of this post which was incomplete and realized that a few days later.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/959/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Large Scale Bayesian Inference for Network Tomography</title>
		<link>http://www.codedanger.com/caglar/archives/933?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=large-scale-bayesian-inference-for-network-tomography</link>
		<comments>http://www.codedanger.com/caglar/archives/933#comments</comments>
		<pubDate>Thu, 02 Jun 2011 19:41:54 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network Engineering]]></category>
		<category><![CDATA[statistics]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[applications]]></category>
		<category><![CDATA[Bayesian Inference]]></category>
		<category><![CDATA[EM]]></category>
		<category><![CDATA[MCEM]]></category>
		<category><![CDATA[MCMC]]></category>
		<category><![CDATA[Network Tomography]]></category>
		<category><![CDATA[Queuing Networks]]></category>
		<category><![CDATA[Topology Inducing]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=933</guid>
		<description><![CDATA[1 Introduction Major goal of network tomography is to infer the internal characteristics of network by only using data from the end nodes. Each node can either be a computer, router or a subnetwork. Broadly speaking large-scale network inference involves estimating network parameters (can be performance or other) based on traffic measurements at a limited subset of nodes [...]]]></description>
			<content:encoded><![CDATA[
<h3><strong>1 Introduction</strong></h3>
<p><strong> </strong><br />
Major goal of network tomography is to infer the internal characteristics of network by only using data from the end nodes. Each node can either be a computer, router or a subnetwork. Broadly speaking large-scale network inference involves estimating network parameters (can be performance or other) based on traffic measurements at a limited subset of nodes [2]. Network tomography assumes that connections can be directional where data travels from origin to destination and the connections can be uni-directional or bidirectional which changes according to the level of abstraction of the model. During the collection of measurements, some of the data can be missing. Some of the reasons of missing data might be either lossy networks, devices’ load or connectionless UDP protocol.<br />
According to data-collection mechanism, there can be 2 types of network tomography:<br />
<em>• Active Tomography:</em> Active network tomography aims to infer the network’s internal characteristics by sending probe packets (or uses traceroute) from ends.<br />
<em>• Passive Tomography:</em> Passive network tomography infers network information from passive observations of regular network traffic.</p>
<p>Some of the problems in literature about network-tomography (NT) that we are trying to solve are:</p>
<p><em>• Link-level measurement inference: </em>This is the characterization of latent variables like delay from the observed measurements at the links of network.<br />
<em>• Network topology inference: </em>The task of inferring the network’s topology by only using the end-to-end measurements.<br />
<em>• Sender-Receiver traffic intensity:</em> This is also known as traffic matrices estimation. The task is to estimate the intensity of traffic between two sources.<br />
<em>• Network Anomography:</em> This is the task of inferring anomalies in the network(might be caused by malfunctioning component, malwares or attacks like DDOS) using only the data from the ends.</p>
<p>The mathematical characterization of network tomography problem can be stated as[1]:</p>
<p>Given observations $$Y (t) := [Y_1 (t) . . . Y_l (t)]$$ , over times $$t = 1 . . . T$$ and a matrix $$A(l×κ)$$ such that $$Y (t) = AX(t), ∀t$$ we want to measure the latent variables $$X(t) := [X1 (t) . . . Xκ (t)]$$ over times $$t = 1 . . . T $$. It is always $$κ ≥ l$$ and in general $$κ = O(l^2 )$$.</p>
<p>Many network tomography problems can be approximated by the linear (not necessarily Gaussian) model $$Y (t) = AX(t) + e$$ where X is the $$κ$$ dimensional vector of network dynamic parameters(ex: delay, loss&#8230;etc), $$Y$$ is a $$l$$ dimensional measurement vector and hence $$A$$ is the $$l × κ$$ routing matrix. It is difficult to measure the traffic matrices directly. Therefore we try to estimate it by using statistical techniques like maximum entropy[12].</p>
<p>&nbsp;</p>
<h3><strong>2 Related Works</strong></h3>
<p><strong> </strong><br />
The term network tomography was first used by Vardi (1996)[11] to capture the similarities between Origin-Destination(OD) traffic matrix estimation through link counts: in network inference, it is common that one does not observe quantities of interest but their aggregations instead and this goes beyond OD estimation. Vardi, also devised the linear tomography Poisson model for OD traffic estimation and the linear form [11] is shown later to approximate other network tomography problems [2]. Network Tomography tries to infer the latent variables and usually observed variables of the data is very limited. In that sense Network Tomography is an ill-posed inverse problem. Current approaches in network tomography uses a limited number of measurements to infer the network performance parameters, by using:</p>
<p>• Maximum Likelihood Estimator.<br />
• Bayesian Inference.</p>
<p>and assuming a prior model.</p>
<p>Venkata et al(2003)[7], used Bayesian inference with Gibbs sampling for only using a number of lost and number of sent packets throughout the network. But although their model could give information about bottlenecks in the network, the model’s accuracy suffers. Nowak et al [2] [3] used MCMC to estimate MAP and EM to estimate MLE of the delays. In [6] Liang et al developed a pseudo EM to maximize the pseudo log-likelihood function. In order to illustrate the pseudo likelihood proposal, they inferred the internal link delay distribution and OD matrix estimation from link measurements. M. Rabbat et al in [8] inferred the network structure from the co-occurence data. Network elements that co-occur in many observations are assumed to be closely connected. Particularly, network elements that co-occur in many observations are probably closely connected and they modeled the co-occurrence observations as independent realizations of a random walk on the graph, subjected to a random permutation which accounts for the lack of order information. Treating the permutations as missing data, Rabbat et al employed MCEM algorithm with importance sampling for estimating the random walk parameters. As a result they were able get an accurate model of the network.</p>
<p>&nbsp;</p>
<h3><strong>3 Possible Approaches to Attack the Problem</strong></h3>
<p><strong> </strong><br />
Queue management is an important aspect of routers. Routers have several interfaces (inif-ingrees, outif-egress) which each link is connected to and the data comes from these interfaces processed by a FPGA or specific multi-core CPU’s. Packets from different queues are processed in a FCFS and round-robin way. Hence it is a natural way to use queuing networks to model the routers’ behavior. Internet is built on the distributed networks scattered around the world and naturally measurements in the end-points can be modeled with queuing networks and graphical models which also allows us to apply Markov chain Monte Carlo for the missing data. C Sutton et al developed a model for Bayesian inference in queuing networks [10], [9] and obtained satisfactory results in their test for the web servers. In a similar fashion, using queuing networks for network tomography might be a more realistic model. Thus I expect that it will yield better accuracy for the estimation of throughput and RTT (round trip-time). Because the large amount of data-processing we’ll need to parallelize and adapt scalable approaches for the machine learning algorithms to be used.Sensor-networks are becoming more ubiquitous and Internet is moving from client-server architecture to the P2P architecture. These networks have specific importance in network tomography. Because there is no other efficient way to have information about the networks internal characteristics. There are some challenges that network tomogoraphy for these networks are bringing to like massive data load and lack of ends. Because every node can be an end. Thus there is no specific end. It might be more efficient to get measurements from supernodes. Network coding[4] is a new technique for modeling network and it has many applications in network tomography. This model is very suitable for bayesian causality and belief propagation. The possibilities should be investigated. Apart from the network’s internal characteristics, it is possible to approximate the router’s internal characteristics like cpu load and temperature with a sampler like MCMC.</p>
<p>With the recent revision of SNMP protocol it is possible to get different types of measurements from MIB’s like the number of in and out connections of a host (this data can be obtained from SNMPv2 by implementing a simple SNMP agent). It is possible to predict device’s connection behavior in an evolving network similar to the social network analysis and protein-protein interaction predictions. This problem is highly structured and device’s behavior is highly correlated with the number of incoming and outgoing connections. Therefore I believe it is possible to use CRF for network’s hosts’ behavior analysis [5]. Flow exporting from routers is an expensive procedure so routers use sampling (e.g.: trajectory sampling) and the missing data problem in that case can be solved with MCMC by sampling from the posterior distribution.</p>
<h3><strong>References</strong></h3>
<p><strong> </strong><br />
[1] E.M. Airoldi and C.N. Faloutsos. Advances in network tomography. Citeseer, 2003.<br />
[2] A. Coates, AO Hero Iii, R. Nowak, and B. Yu. Internet tomography. Signal Processing Magazine, IEEE, 19(3):47–65, 2002.<br />
[3] M.J. Coates and R.D. Nowak. Network tomography for internal delay estimation. In Acoustics, Speech, and Signal Processing, 2001. Proceedings.(ICASSP’01). 2001 IEEE International Conference on, volume 6, pages 3409–3412. IEEE, 2002.<br />
[4] C. Fragouli, J. Le Boudec, and J. Widmer. Network coding: an instant primer. Computer Communication Review, 36(1):63, 2006.<br />
[5] T. Karagiannis, K. Papagiannaki, and M. Faloutsos. BLINC: multilevel traffic classification in the dark. In Proceedings of the 2005 conference on Applications, technologies, architectures, and protocols for computer communications,pages 229–240. ACM, 2005.<br />
[6] G. Liang and B. Yu. Maximum pseudo likelihood estimation in network tomography. Signal Processing, IEEE Transactions on, 51(8):2043–2053, 2003.<br />
[7] V.N. Padmanabhan, L. Qiu, and H.J. Wang. Passive network tomography using bayesian inference. In Proceedings of the 2nd ACM SIGCOMM Workshop on Internet measurement, pages 93–94. ACM, 2002.<br />
[8] M.G. Rabbat, M.A.T. Figueiredo, and R.D. Nowak. Network inference from co-occurrences. Information Theory, IEEE Transactions on, 54(9):4053–4068, 2008.<br />
[9] C. Sutton and M.I. Jordan. Inference and Learning in Networks of Queues. 3<br />
[10] C. Sutton and M.I. Jordan. Bayesian Inference for Queueing Networks and Modeling of Internet Services. Arxiv preprint arXiv:1001.3355, 2010.<br />
[11] Y. Vardi. Network Tomography: Estimating Source-Destination Traffic Intensities from Link Data. Journal of the American Statistical Association, 91(433),1996.<br />
[12] Y. Zhang, M. Roughan, C. Lund, and D. Donoho. An information-theoretic approach to traffic matrix estimation. In Proceedings of the 2003 conference on Applications, technologies, architectures, and protocols for computer communications, pages 301–312. ACM, 2003.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/933/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Math behind the Quantum Computers</title>
		<link>http://www.codedanger.com/caglar/archives/917?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=math-behind-the-quantum-computers</link>
		<comments>http://www.codedanger.com/caglar/archives/917#comments</comments>
		<pubDate>Thu, 14 Apr 2011 18:25:37 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[research]]></category>
		<category><![CDATA[science]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[quantum]]></category>
		<category><![CDATA[quantum computers]]></category>
		<category><![CDATA[theoretical computer science]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=917</guid>
		<description><![CDATA[AMS has excellent math articles for introductory and general audience in a series of feature columns every month. Luckily those articles are accessible from the web. Recently I noticed two very interesting articles on mathematics behind the quantum computers. The articles can be accessed from those links part 1 and part 2.  The math described [...]]]></description>
			<content:encoded><![CDATA[<p>AMS has excellent math articles for introductory and general audience in a series of feature columns every month. Luckily those articles are accessible from the web. Recently I noticed two very interesting articles on mathematics behind the quantum computers. The articles can be accessed from those links <a title="The Mathematics Behind Quantum Computing: Part I " href="http://www.ams.org/samplings/feature-column/fcarc-quantum-one" target="_blank">part 1</a> and<a title="The Mathematics Behind Quantum Computing: Part II" href="http://www.ams.org/samplings/feature-column/fcarc-quantum-two" target="_blank"> part 2</a>.  The math described in those articles are not very advanced and it can be thought as an introductory math text, but if you are interested in the topic, I suggest you to have a look at these articles.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/917/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Matlab Commands in NumPy and R</title>
		<link>http://www.codedanger.com/caglar/archives/913?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-commands-in-numpy-and-r</link>
		<comments>http://www.codedanger.com/caglar/archives/913#comments</comments>
		<pubDate>Sat, 02 Apr 2011 18:50:32 +0000</pubDate>
		<dc:creator>caglar</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[research]]></category>
		<category><![CDATA[science]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[matlab]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[table]]></category>

		<guid isPermaLink="false">http://www.codedanger.com/caglar/?p=913</guid>
		<description><![CDATA[There is a very nice pdf prepared by V. B. Gunderson for the correspondents of Matlab commands in numpy and R. You can access the pdf version of document by clicking here. Take note this site, one day you may need it .]]></description>
			<content:encoded><![CDATA[<p>There is a very nice pdf prepared by V. B. Gunderson for the correspondents of Matlab commands in numpy and R. You can access the pdf version of document by clicking <a href="http://sml.nicta.com.au/isml10/tutorials/matlab-python-xref.pdf">here</a>. Take note this site, one day you may need it <img src='http://www.codedanger.com/caglar/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedanger.com/caglar/archives/913/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

