you are getting reflections from the front ( glass surface ) and back ( mirrored ) surface, including ( multiple ) internal reflections : it should be obvious from this diagram that the spots will be further apart as you move to a more glancing angle of incidence. depending on the polarization of the laser pointer, there is an angle ( the brewster angle ) where you can make the front ( glass ) surface reflection disappear completely. this takes some experimenting. the exact details of the intensity as a function of angle of incidence are described by the fresnel equations. from that wikipedia article, here is a diagram showing how the intensity of the ( front ) reflection changes with angle of incidence and polarization : this effect is independent of wavelength ( except inasmuch as the refractive index is a weak function of wavelength... so different colors of light will have a slightly different brewster angle ) ; the only way in which laser light is different from " ordinary " light in this case is the fact that laser light is typically linearly polarized, so that the reflection coefficient for a particular angle can be changed simply by rotating the laser pointer. as rainer p pointed out in a comment, if there is a coefficient of reflection $ c $ at the front face, then $ ( 1 - c ) $ of the intensity makes it to the back ; and if the coefficient of reflection at the inside of the glass / air interface is $ r $, then the successive reflected beams will have intensities that decrease geometrically : $ $ c, ( 1 - c ) ( 1 - r ), ( 1 - c ) ( 1 - r ) r, ( 1 - c ) ( 1 - r ) r ^ 2, ( 1 - c ) ( 1 - r ) r ^ 3,... $ $ of course the reciprocity theorem tells us that when we reverse the direction of a beam, we get the same reflectivity, so $ r = c $. this means the above can be simplified ; but i left it in this form to show better what interactions the rays undergo. the above also assumes perfect reflection at the silvered ( back ) face : it should be easy to see how you could add that term...


the planet neptune's discovery was an example of something similar to this. it was known that newtons's equations gave the wrong description of the motion of uranus and mercury. urbain le verrier sat down and tried to see what would happen if we assumed that the equations were right and the universe was wrong. he set up a complicated system of equations that incorporated a lot of ways contemporary knowledge of the universe could wrong, including the number of planets, the location and mass of the planets, and the presences of the forces other than gravity. he would eventually find a solution to the equations where the dominating error was the presence of another, as of yet undetected, planet. his equations gave the distance from the sun and the mass of the planet correctly, as well as enough detail about the planet's location in the sky that it was found with only an hour of searching. mercury's orbit's issues would eventually be solved by general relativity.


finite element : volumetric integrals, internal polynomial order classical finite element methods assume continuous or weakly continuous approximation spaces and ask for volumetric integrals of the weak form to be satisfied. the order of accuracy is increased by raising the approximation order within elements. the methods are not exactly conservative, thus often struggle with stability for discontinuous processes. finite volume : surface integrals, fluxes from discontinuous data, reconstruction order finite volume methods use piecewise constant approximation spaces and ask for integrals against piecewise constant test functions to be satisfied. this yields exact conservation statements. the volume integral is converted to a surface integral and the entire physics is specified in terms of fluxes in those surface integrals. for first - order hyperbolic problems, this is a riemann solve. second order / elliptic fluxes are more subtle. order of accuracy is increased by using neighbors to ( conservatively ) reconstruct higher order representations of the state inside elements ( slope reconstruction / limiting ) or by reconstructing fluxes ( flux limiting ). the reconstruction process is usually nonlinear to control oscillations around discontinuous features of the solution, see total variation diminishing ( tvd ) and essentially non - oscillatory ( eno / weno ) methods. a nonlinear discretization is necessary to simultaneously obtain both higher than first order accuracy in smooth regions and bounded total variation across discontinuities, see godunov's theorem. comments both fe and fv are easy to define up to second order accuracy on unstructured grids. fe is easier to go beyond second order on unstructured grids. fv handles non - conforming meshes more easily and robustly. combining fe and fv the methods can be married in multiple ways. discontinuous galerkin methods are finite element methods that use discontinuous basis functions, thus acquiring riemann solvers and more robustness for discontinuous processes ( especially hyperbolic ). dg methods can be used with nonlinear limiters ( usually with some reduction in accuracy ), but satisfy a cell - wise entropy inequality without limiting and can thus be used without limiting for some problems where other schemes require limiters. ( this is especially useful for adjoint - based optimization since it makes the discrete adjoint more representative of the continuous adjoint equations. ) mixed fe methods for elliptic problems use discontinuous basis functions and after some choices of quadrature, can be reinterpreted as standard


finite volume methods, see this answer for more. reconstruction dg methods ( aka. $ p _ n p _ m $ or " recovery dg " ) use both fv - like conservative reconstruction and internal order enrichment, and are thus a superset of fv and dg methods.


another example : euler's sum of powers conjecture, a generalization of fermat's last theorem. it states : if the equation $ \ sum _ { i = 1 } ^ kx _ i ^ n = z ^ n $ has a solution in positive integers, then $ n \ leq k $ ( unless $ k = 1 $ ). fermat's last theorem is the $ k = 2 $ case of this conjecture. a counterexample for $ n = 5 $ was found in 1966 : it's $ $ 61917364224 = 27 ^ 5 + 84 ^ 5 + 110 ^ 5 + 133 ^ 5 = 144 ^ 5 $ $ the smallest counterexample for $ n = 4 $ was found in 1988 : $ $ 31858749840007945920321 = 95800 ^ 4 + 217519 ^ 4 + 414560 ^ 4 = 422481 ^ 4 $ $ this example used to be even more useful in the days before flt was proved, as an answer to the question " why do we need to prove flt if it has been verified for thousands of numbers? " : - )


the previous answers all restate the problem as " work is force dot / times distance ". but this is not really satisfying, because you could then ask " why is work force dot distance? " and the mystery is the same. the only way to answer questions like this is to rely on symmetry principles, since these are more fundamental than the laws of motion. using galilean invariance, the symmetry that says that the laws of physics look the same to you on a moving train, you can explain why energy must be proportional to the mass times the velocity squared. first, you need to define kinetic energy. i will define it as follows : the kinetic energy $ e ( m, v ) $ of a ball of clay of mass $ m $ moving with velocity $ v $ is the amount of calories of heat that it makes when it smacks into a wall. this definition does not make reference to any mechanical quantity, and it can be determined using thermometers. i will show that, assuming galilean invariance, $ e ( v ) $ must be the square of the velocity. $ e ( m, v ) $, if it is invariant, must be proportional to the mass, because you can smack two clay balls side by side and get twice the heating, so $ $ e ( m, v ) = m e ( v ) $ $ further, if you smack two identical clay balls of mass $ m $ moving with velocity $ v $ head - on into each other, both balls stop, by symmetry. the result is that each acts as a wall for the other, and you must get an amount of heating equal to $ 2m e ( v ) $. but now look at this in a train which is moving along with one of the balls before the collision. in this frame of reference, the first ball starts out stopped, the second ball hits it at $ 2v $, and the two - ball stuck system ends up moving with velocity $ v $. the kinetic energy of the second ball is $ me ( 2v ) $ at the start, and after the collision, you have $ 2me ( v ) $ kinetic energy stored in the combined ball. but the heating generated by the collision is the same as in the earlier case. so there are now two $ 2me ( v ) $ terms to consider : one representing the heat generated by the collision, which we saw earlier was $ 2me ( v ) $, and the other representing the energy stored in the


moving, double - mass ball, which is also $ 2me ( v ) $. due to conservation of energy, those two terms need to add up to the kinetic energy of the second ball before the collision : $ $ me ( 2v ) = 2me ( v ) + 2me ( v ) $ $ $ $ e ( 2v ) = 4 e ( v ) $ $ which implies that $ e $ is quadratic. non - circular force - times - distance here is the non - circular version of the force - times - distance argument that everyone seems to love so much, but is never done correctly. in order to argue that energy is quadratic in velocity, it is enough to establish two things : potential energy on the earth's surface is linear in height objects falling on the earth's surface have constant acceleration the result then follows. that the energy in a constant gravitational field is proportional to the height is established by statics. if you believe the law of the lever, an object will be in equilibrium with another object on a lever when the distances are inversely proportional to the masses ( there are simple geometric demonstrations of this that require nothing more than the fact that equal mass objects balance at equal center - of - mass distances ). then if you tilt the lever a little bit, the mass - times - height gained by 1 is equal to the mass - times - height gained by the other. this allows you to lift objects and lower them with very little effort, so long as the mass - times - height added over all the objects is constant before and after. this is archimedes'principle. another way of saying the same thing uses an elevator, consisting of two platforms connected by a chain through a pulley, so that when one goes up, the other goes down. you can lift an object up, if you lower an equal amount of mass down the same amount. you can lift two objects a certain distance in two steps, if you drop an object twice as far. this establishes that for all reversible motions of the elevator, the ones that do not require you to do any work ( in both the colloquial sense and the physics sense - - - the two notions coincide here ), the mass - times - height summed over all the objects is conserved. the " energy " can now be defined as that quantity of motion which is conserved when these objects are allowed to move with a non - infinitesimal velocity. this is feynman's version of archimedes


. so the mass - times - height is a measure of the effort required to lift something, and it is a conserved quantity in statics. this quantity should be conserved even if there is dynamics in intermediate stages. by this i mean that if you let two weights drop while suspended on a string, let them do an elastic collision, and catch the two objects when they stop moving again, you did no work. the objects should then go up to the same total mass - times - height. this is the original demonstration of the laws of elastic collisions by christian huygens, who argued that if you drop two masses on pendulums, and let them collide, their center of mass has to go up to the same height, if you catch the balls at their maximum point. from this, huygens generalized the law of conservation of potential energy implicit in archimedes to derive the law of conservation of square - velocity in elastic collisions. his principle that the center of mass cannot be raised by dynamic collisions is the first statement of conservation of energy. for completeness, the fact that an object accelerates in a constant gravitational field with uniform acceleration is a consequence of galilean invariance, and the assumption that a gravitational field is frame invariant to uniform motions up and down with a steady velocity. once you know that motion in constant gravity is constant acceleration, you know that $ $ mv ^ 2 / 2 + mgh = c $ $ so that huygens dynamical quantity which is additively conserved along with archimedes mass times height is the velocity squared.


gpus are bad at doing one thing at a time. a modern high - end gpu may have several thousand cores, but these are organized into simd blocks of 16 or 32. if you want to compute 2 + 2, you might have 32 cores each compute an addition operation, and then discard 31 of the results. gpus are bad at doing individual things fast. gpus only recently topped the one - gigahertz mark, something that cpus did more than twenty years ago. if your task involves doing many things to one piece of data, rather than one thing to many pieces of data, a cpu is far better. gpus are bad at dealing with data non - locality. the hardware is optimized for working on contiguous blocks of data. if your task involves picking up individual pieces of data scattered around your data set, the gpu's incredible memory bandwidth is mostly wasted.


here are a few. the first one is included because it's not very well known and is not general, though the ones that follow are very general and very useful. a great but not very well known way to find the primitive of $ f ^ { - 1 } $ in terms of the primitive of $ f $, $ f $, is ( very easy to prove : just differentiate both sides and use the chain rule ) : $ $ \ int f ^ { - 1 } ( x ) \, dx = x \ cdot f ^ { - 1 } ( x ) - ( f \ circ f ^ { - 1 } ) ( x ) + c. $ $ examples : $ $ \ begin { aligned } \ displaystyle \ int \ arcsin ( x ) \, dx & = x \ cdot \ arcsin ( x ) - ( - \ cos \ circ \ arcsin ) ( x ) + c \ \ & = x \ cdot \ arcsin ( x ) + \ sqrt { 1 - x ^ 2 } + c. \ end { aligned } $ $ $ $ \ begin { aligned } \ int \ log ( x ) \, dx & = x \ cdot \ log ( x ) - ( \ exp \ circ \ log ) ( x ) + c \ \ & = x \ cdot \ left ( \ log ( x ) - 1 \ right ) + c. \ end { aligned } $ $ this one is more well known, and extremely powerful, it's called differentiating under the integral sign. it requires ingenuity most of the time to know when to apply, and how to apply it, but that only makes it more interesting. the technique uses the simple fact that $ $ \ frac { \ mathrm d } { \ mathrm d x } \ int _ a ^ b f \ left ( { x, y } \ right ) \ mathrm d y = \ int _ a ^ b \ frac { \ partial f } { \ partial x } \ left ( { x, y } \ right ) \ mathrm d y. $ $ example : we want to calculate the integral $ \ int _ { 0 } ^ { \ infty } \ frac { \ sin ( x ) } { x } dx $. to do that, we unintuitively consider the more complicated integral $ \ int _ { 0 } ^ { \ infty } e ^


{ - tx } \ frac { \ sin ( x ) } { x } dx $ instead. let $ $ i ( t ) = \ int _ { 0 } ^ { \ infty } e ^ { - tx } \ frac { \ sin ( x ) } { x } dx, $ $ then $ $ i'( t ) = - \ int _ { 0 } ^ { \ infty } e ^ { - tx } \ sin ( x ) dx = \ frac { e ^ { - t x } ( t \ sin ( x ) + \ cos ( x ) ) } { t ^ 2 + 1 } \ bigg | _ 0 ^ { \ infty } = \ frac { - 1 } { 1 + t ^ 2 }. $ $ since both $ i ( t ) $ and $ - \ arctan ( t ) $ are primitives of $ \ frac { - 1 } { 1 + t ^ 2 } $, they must differ only by a constant, so that $ i ( t ) + \ arctan ( t ) = c $. let $ t \ to \ infty $, then $ i ( t ) \ to 0 $ and $ - \ arctan ( t ) \ to - \ pi / 2 $, and hence $ c = \ pi / 2 $, and $ i ( t ) = \ frac { \ pi } { 2 } - \ arctan ( t ) $. finally, $ $ \ int _ { 0 } ^ { \ infty } \ frac { \ sin ( x ) } { x } dx = i ( 0 ) = \ frac { \ pi } { 2 } - \ arctan ( 0 ) = \ boxed { \ frac { \ pi } { 2 } }. $ $ this one is probably the most commonly used " advanced integration technique ", and for good reasons. it's referred to as the " residue theorem " and it states that if $ \ gamma $ is a counterclockwise simple closed curve, then $ \ displaystyle \ int _ \ gamma f ( z ) dz = 2 \ pi i \ sum _ { k = 1 } ^ n \ operatorname { res } ( f, a _ k ) $. it will be difficult for you to understand this one without knowledge in complex analysis, but you can get the gist of it with the wiki article. example : we


want to compute $ \ int _ { - \ infty } ^ { \ infty } \ frac { x ^ 2 } { 1 + x ^ 4 } dx $. the poles of our function $ f ( z ) = \ frac { x ^ 2 } { 1 + x ^ 4 } $ in the upper half plane are $ a _ 1 = e ^ { i \ frac { \ pi } { 4 } } $ and $ a _ 2 = e ^ { i \ frac { 3 \ pi } { 4 } } $. the residues of our function at those points are $ $ \ operatorname { res } ( f, a _ 1 ) = \ lim _ { z \ to a _ 1 } ( z - a _ 1 ) f ( z ) = \ frac { e ^ { i \ frac { - \ pi } { 4 } } } { 4 }, $ $ and $ $ \ operatorname { res } ( f, a _ 2 ) = \ lim _ { z \ to a _ 2 } ( z - a _ 2 ) f ( z ) = \ frac { e ^ { i \ frac { - 3 \ pi } { 4 } } } { 4 }. $ $ let $ \ gamma $ be the closed path around the boundary of the semicircle of radius $ r > 1 $ on the upper half plane, traversed in the counter - clockwise direction. then the residue theorem gives us $ { 1 \ over 2 \ pi i } \ int _ \ gamma f ( z ) \, dz = \ operatorname { res } ( f, a _ 1 ) + \ operatorname { res } ( f, a _ 2 ) = { 1 \ over 4 } \ left ( { 1 - i \ over \ sqrt { 2 } } + { - 1 - i \ over \ sqrt { 2 } } \ right ) = { - i \ over 2 \ sqrt { 2 } } $ and $ \ int _ \ gamma f ( z ) \, dz = { \ pi \ over \ sqrt { 2 } } $. now, by the definition of $ \ gamma $, we have : $ $ \ int _ \ gamma f ( z ) \, dz = \ int _ { - r } ^ r \ frac { x ^ 2 } { 1 + x ^ 4 } dx + \ int _ 0 ^ \ pi { i ( r e ^


{ it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } dz = { \ pi \ over \ sqrt { 2 } }. $ $ for the integral on the semicircle $ $ \ int _ 0 ^ \ pi { i ( r e ^ { it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } dz, $ $ we have $ $ \ begin { aligned } \ left | \ int _ 0 ^ \ pi { i ( r e ^ { it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } dz \ right | & \ leq \ int _ 0 ^ \ pi \ left | { i ( r e ^ { it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } \ right | dz \ \ & \ leq \ int _ 0 ^ \ pi { r ^ 3 \ over r ^ 4 - 1 } dz = { \ pi r ^ 3 \ over r ^ 4 - 1 }. \ end { aligned } $ $ hence, as $ r \ to \ infty $, we have $ { \ pi r ^ 3 \ over r ^ 4 - 1 } \ to 0 $, and hence $ \ int _ 0 ^ \ pi { i ( r e ^ { it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } dz \ to 0 $. finally, $ $ \ begin { aligned } \ int _ { - \ infty } ^ \ infty \ frac { x ^ 2 } { 1 + x ^ 4 } dx & = \ lim _ { r \ to \ infty } \ int _ { - r } ^ r \ frac { x ^ 2 } { 1 + x ^ 4 } dx \ \ & = \ lim _ { r \ to \ infty } { \ pi \ over \ sqrt { 2 } } - \ int _ 0 ^ \ pi { i ( r e ^ { it } ) ^ 3 \ over 1 + ( r e ^ { it } ) ^ 4 } dz = \ boxed { { \ pi \ over \ sqrt { 2 } } }. \ end { aligned } $ $ my final " technique " is the use of the mean value property for complex analytic functions, or cauchy's integral formula in


other words : $ $ \ begin { aligned } f ( a ) & = \ frac { 1 } { 2 \ pi i } \ int _ \ gamma \ frac { f ( z ) } { z - a } \, dz \ \ & = \ frac { 1 } { 2 \ pi } \ int _ { 0 } ^ { 2 \ pi } f \ left ( a + e ^ { ix } \ right ) dx. \ end { aligned } $ $ example : we want to compute the very messy looking integral $ \ int _ 0 ^ { 2 \ pi } \ cos ( \ cos ( x ) + 1 ) \ cosh ( \ sin ( x ) ) dx $. we first notice that $ $ \ begin { aligned } & \ hphantom { = } \ cos [ \ cos ( x ) + 1 ] \ cosh [ \ sin ( x ) ] \ \ & = \ re \ left \ { \ cos [ \ cos ( x ) + 1 ] \ cosh [ \ sin ( x ) ] - i \ sin [ \ cos ( x ) + 1 ] \ sinh [ \ sin ( x ) ] \ right \ } \ \ & = \ re \ left [ \ cos \ left ( 1 + e ^ { i x } \ right ) \ right ]. \ end { aligned } $ $ then, we have $ $ \ begin { aligned } \ int _ 0 ^ { 2 \ pi } \ cos [ \ cos ( x ) + 1 ] \ cosh [ \ sin ( x ) ] dx & = \ int _ 0 ^ { 2 \ pi } \ re \ left [ \ cos \ left ( 1 + e ^ { i x } \ right ) \ right ] dx \ \ & = \ re \ left [ \ int _ 0 ^ { 2 \ pi } \ cos \ left ( 1 + e ^ { i x } \ right ) dx \ right ] \ \ & = \ re \ left ( \ cos ( 1 ) \ cdot 2 \ pi \ right ) = \ boxed { 2 \ pi \ cos ( 1 ) }. \ end { aligned } $ $


fever is a trait observed in warm and cold - blooded vertebrates that has been conserved for hundreds of millions of years ( evans, 2015 ). elevated body temperature stimulates the body's immune response against infectious viruses and bacteria. it also makes the body less favorable as a host for replicating viruses and bacteria, which are temperature sensitive ( source : sci am ). the innate system is stimulated by increasing the recruitment, activation and bacteriolytic activity of neutrophils. likewise, natural killer cells'cytotoxic activity is enhanced and their recruitment is increased, including that to tumors. macrophages and dendritic cells increase their activity in clearing up the mess associated with infection. also the adaptive immune response is enhanced by elevated temperatures. for example, the circulation of t cells to the lymph nodes is increased and their proliferation is stimulated. in fact, taking pain killers that reduce fever have been shown to lead to poorer clearance of pathogens from the body ( evans, 2015 ). in adults, when body temperature reaches 104 of ( 40 oc ) it can become dangerous and fever reducing agents like aspirin are recommended ( source : emedicine ) reference - evans, nat rev immunol ( 2015 ) ; 15 ( 6 ) : 335 – 49


* * warning : lithium ion cells * * while this question relates to non - rechargeable aa cells it is possible that someone may seek to extend the advice to testing other small cells. in the case of li - ion rechargeable cells ( aa, 18650, other ) this can be a very bad idea in some cases. shorting lithium ion cells as in test 2 is liable to be a very bad idea indeed. depending on design, some li - ion cells will provide short circuit current of many times the cell mah rating - eg perhaps 50 + amps for an 18650 cell, and perhaps 10's of amps for an aa size li - ion cell. this level of discharge can cause injury and worst case may destroy the cell, in some uncommon cases with substantial release of energy in the form of flame and hot material. aa non - rechargeable cells : 1 ) ignore the funny answers generally speaking, if a battery is more than 1 year old then only alkaline batteries are worth keeping. shelf life of non - alkaline can be some years but they deteriorate badly with time. modern alkaline have gotten awesome, as they still retain a majority of charge at 3 to 5 years. non brand name batteries are often ( but not always ) junk. heft battery in hand. learn to get the feel of what a " real " aa cell weighs. an eveready or similar alkaline will be around 30 grams / one ounce. an aa nimh 2500 mah will be similar. anything under 25g is suspect. under 20g is junk. under 15g is not unknown. 2 ) brutal but works set multimeter to high current range ( 10a or 20a usually ). needs both dial setting and probe socket change in most meters. use two sharpish probes. if battery has any light surface corrosion scratch a clean bright spot with probe tip. if it has more than surface corrosion consider binning it. some alkaline cells leak electrolyte over time, which is damaging to gear and annoying ( at least ) to skin. press negative probe against battery base. move slightly to make scratching contact. press firmly. do not slip so probe jumps off battery and punctures your other hand. not advised. ask me how i know. press positive probe onto top of battery. hold for maybe 1 second. perhaps 2. experience will show what is needed. this is thrashing the battery, decreasing its life and making it


sad. try not to do this often or for very long. top aa alkaline cells new will give 5 - 10 a. ( nimh aa will approach 10a for a good cell ). lightly used aa or ones which have had bursts of heavy use and then recovered will typically give a few amps. deader again will be 1 - 3a. anything under 1 a you probably want to discard unless you have a micropower application. non alkaline will usually be lower. i buy only alkaline primary cells as other " quality " cells are usually not vastly cheaper but are of much lower capacity. current will fall with time. a very good cell will fall little over 1 to maybe 2 seconds. more used cells will start lower and fall faster. well used cells may plummet. i place cells in approximate order of current after testing. the top ones can be grouped and wrapped with a rubber band. the excessively keen may mark the current given on the cell with a marker. absolute current is not the point - it serves as a measure of usefulness. 3 ) gentler - but works reasonably well. set meter to 2v range or next above 2v if no 2v range. measure battery unloaded voltage. new unused alkaline are about 1. 65v. most books don't tell you that. unused but sat on the shelf 1 year + alkaline will be down slightly. maybe 1. 55 - 1. 6v modestly used cells will be 1. 5v + used but useful may be 1. 3v - 1. 5v range after that it's all downhill. a 1v oc cell is dodo dead. a 1. 1v -. 2v cell will probably load down to 1v if you look at it harshly. do this a few times and you will get a feel for it. 4 ) in between. use a heavyish load and measure voltage. keep a standard resistor for this. solder the wires on that you use as probes. a twisted connection has too much variability. resistor should draw a heavy load for battery type used. 100 ma - 500 ma is probably ok. battery testers usually work this way. 5 ) is this worth doing? yes, it is. as well as returning a few batteries to the fold and making your life more exciting when some fail to perform, it teaches you a new skill that can be helpful in understanding how batteries behave in real life and the possible effect on equipment


. the more you know, the more you get to know, and this is one more tool along the path towards knowing everything : - ). [ the path is rather longer than any can traverse, but learning how to run along it can be fun ].


your question implies that aic and bic try to answer the same question, which is not true. the aic tries to select the model that most adequately describes an unknown, high dimensional reality. this means that reality is never in the set of candidate models that are being considered. on the contrary, bic tries to find the true model among the set of candidates. i find it quite odd the assumption that reality is instantiated in one of the models that the researchers built along the way. this is a real issue for bic. nevertheless, there are a lot of researchers who say bic is better than aic, using model recovery simulations as an argument. these simulations consist of generating data from models a and b, and then fitting both datasets with the two models. overfitting occurs when the wrong model fits the data better than the generating. the point of these simulations is to see how well aic and bic correct these overfits. usually, the results point to the fact that aic is too liberal and still frequently prefers a more complex, wrong model over a simpler, true model. at first glance these simulations seem to be really good arguments, but the problem with them is that they are meaningless for aic. as i said before, aic does not consider that any of the candidate models being tested is actually true. according to aic, all models are approximations to reality, and reality should never have a low dimensionality. at least lower than some of the candidate models. my recommendation is to use both aic and bic. most of the times they will agree on the preferred model, when they don't, just report it. if you are unhappy with both aic and bic and have free time to invest, look up minimum description length ( mdl ), a totally different approach that overcomes the limitations of aic and bic. there are several measures stemming from mdl, like normalized maximum likelihood or the fisher information approximation. the problem with mdl is that its mathematically demanding and / or computationally intensive. still, if you want to stick to simple solutions, a nice way for assessing model flexibility ( especially when the number of parameters are equal, rendering aic and bic useless ) is doing parametric bootstrap, which is quite easy to implement. here is a link to a paper on it. some people here advocate for the use of cross - validation. i personally have used it and don't have anything against it, but


the issue with it is that the choice among the sample - cutting rule ( leave - one - out, k - fold, etc ) is an unprincipled one.


the simple answer is that no, the big bang did not happen at a point. instead, it happened everywhere in the universe at the same time. consequences of this include : the universe doesn't have a centre : the big bang didn't happen at a point so there is no central point in the universe that it is expanding from. the universe isn't expanding into anything : because the universe isn't expanding like a ball of fire, there is no space outside the universe that it is expanding into. in the next section, i'll sketch out a rough description of how this can be, followed by a more detailed description for the more determined readers. a simplified description of the big bang imagine measuring our current universe by drawing out a grid with a spacing of 1 light year. although obviously, we can't do this, you can easily imagine putting the earth at ( 0, 0 ), alpha centauri at ( 4. 37, 0 ), and plotting out all the stars on this grid. the key thing is that this grid is infinite $ ^ 1 $ i. e. there is no point where you can't extend the grid any further. now wind time back to 7 billion years after the big bang, i. e. about halfway back. our grid now has a spacing of half a light year, but it's still infinite - there is still no edge to it. the average spacing between objects in the universe has reduced by half and the average density has gone up by a factor of $ 2 ^ 3 $. now wind back to 0. 0000000001 seconds after the big bang. there's no special significance to that number ; it's just meant to be extremely small. our grid now has a very small spacing, but it's still infinite. no matter how close we get to the big bang we still have an infinite grid filling all of space. you may have heard pop science programs describing the big bang as happening everywhere and this is what they mean. the universe didn't shrink down to a point at the big bang, it's just that the spacing between any two randomly selected spacetime points shrank down to zero. so at the big bang, we have a very odd situation where the spacing between every point in the universe is zero, but the universe is still infinite. the total size of the universe is then $ 0 \ times \ infty $, which is undefined. you probably think this doesn


' t make sense, and actually, most physicists agree with you. the big bang is a singularity, and most of us don't think singularities occur in the real universe. we expect that some quantum gravity effect will become important as we approach the big bang. however, at the moment we have no working theory of quantum gravity to explain exactly what happens. $ ^ 1 $ we assume the universe is infinite - more on this in the next section for determined readers only to find out how the universe evolved in the past, and what will happen to it in the future, we have to solve einstein's equations of general relativity for the whole universe. the solution we get is an object called the metric tensor that describes spacetime for the universe. but einstein's equations are partial differential equations, and as a result, have a whole family of solutions. to get the solution corresponding to our universe we need to specify some initial conditions. the question is then what initial conditions to use. well, if we look at the universe around us we note two things : if we average over large scales the universe looks the same in all directions, that is it is isotropic if we average over large scales the universe is the same everywhere, that is it is homogeneous you might reasonably point out that the universe doesn't look very homogeneous since it has galaxies with a high density randomly scattered around in space with a very low density. however, if we average on scales larger than the size of galaxy superclusters we do get a constant average density. also, if we look back to the time the cosmic microwave background was emitted ( 380, 000 years after the big bang and well before galaxies started to form ) we find that the universe is homogeneous to about $ 1 $ part in $ 10 ^ 5 $, which is pretty homogeneous. so as the initial conditions let's specify that the universe is homogeneous and isotropic, and with these assumptions, einstein's equation has a ( relatively! ) simple solution. indeed this solution was found soon after einstein formulated general relativity and has been independently discovered by several different people. as a result the solution glories in the name friedmann – lemaitre – robertson – walker metric, though you'll usually see this shortened to flrw metric or sometimes frw metric ( why lemaitre misses out i'm not sure ). recall the grid i described to measure out the universe in the first section of this answer, and how i described the grid shrinking as


we went back in time towards the big bang? well the flrw metric makes this quantitative. if $ ( x, y, z ) $ is some point on our grid then the current distance to that point is just given by pythagoras'theorem : $ $ d ^ 2 = x ^ 2 + y ^ 2 + z ^ 2 $ $ what the flrw metric tells us is that the distance changes with time according to the equation : $ $ d ^ 2 ( t ) = a ^ 2 ( t ) ( x ^ 2 + y ^ 2 + z ^ 2 ) $ $ where $ a ( t ) $ is a function called the [ scale factor ]. we get the function for the scale factor when we solve einstein's equations. sadly it doesn't have a simple analytical form, but it's been calculated in answers to the previous questions what was the density of the universe when it was only the size of our solar system? and how does the hubble parameter change with the age of the universe?. the result is : the value of the scale factor is conventionally taken to be unity at the current time, so if we go back in time and the universe shrinks we have $ a ( t ) < 1 $, and conversely in the future as the universe expands we have $ a ( t ) > 1 $. the big bang happens because if we go back to time to $ t = 0 $ the scale factor $ a ( 0 ) $ is zero. this gives us the remarkable result that the distance to any point in the universe $ ( x, y, z ) $ is : $ $ d ^ 2 ( t ) = 0 ( x ^ 2 + y ^ 2 + z ^ 2 ) = 0 $ $ so the distance between every point in the universe is zero. the density of matter ( the density of radiation behaves differently but let's gloss over that ) is given by : $ $ \ rho ( t ) = \ frac { \ rho _ 0 } { a ^ 3 ( t ) } $ $ where $ \ rho _ 0 $ is the density at the current time, so the density at time zero is infinitely large. at the time $ t = 0 $ the flrw metric becomes singular. no one i know thinks the universe did become singular at the big bang. this isn't a modern opinion : the first person i know to have objected publically was fred hoyle, and he suggested steady state theory


to avoid the singularity. these days it's commonly believed that some quantum gravity effect will prevent the geometry from becoming singular, though since we have no working theory of quantum gravity no one knows how this might work. so to conclude : the big bang is the zero time limit of the flrw metric, and it's a time when the spacing between every point in the universe becomes zero and the density goes to infinity. it should be clear that we can't associate the big bang with a single spatial point because the distance between all points was zero so the big bang happened at all points in space. this is why it's commonly said that the big bang happened everywhere. in the discussion above i've several times casually referred to the universe as infinite, but what i really mean is that it can't have an edge. remember that our going - in assumption is that the universe is homogeneous i. e. it's the same everywhere. if this is true the universe can't have an edge because points at the edge would be different from points away from the edge. a homogenous universe must either be infinite, or it must be closed i. e. have the spatial topology of a 3 - sphere. the recent planck results show the curvature is zero to within experimental error, so if the universe is closed the scale must be far larger than the observable universe.


this is partly a matter of terminology, and as such, only requires that you and the person you're talking to clarify it beforehand. however, there are different topics that are more strongly associated with parallelism, concurrency, or distributed systems. parallelism is generally concerned with accomplishing a particular computation as fast as possible, exploiting multiple processors. the scale of the processors may range from multiple arithmetical units inside a single processor, to multiple processors sharing memory, to distributing the computation on many computers. on the side of models of computation, parallelism is generally about using multiple simultaneous threads of computation internally, in order to compute a final result. parallelism is also sometimes used for real - time reactive systems, which contain many processors that share a single master clock ; such systems are fully deterministic. concurrency is the study of computations with multiple threads of computation. concurrency tends to come from the architecture of the software rather than from the architecture of the hardware. software may be written to use concurrency in order to exploit hardware parallelism, but often the need is inherent in the software's behavior, to react to different asynchronous events ( e. g. a computation thread that works independently of a user interface thread, or a program that reacts to hardware interrupts by switching to an interrupt handler thread ). distributed computing studies separate processors connected by communication links. whereas parallel processing models often ( but not always ) assume shared memory, distributed systems rely fundamentally on message passing. distributed systems are inherently concurrent. like concurrency, distribution is often part of the goal, not solely part of the solution : if resources are in geographically distinct locations, the system is inherently distributed. systems in which partial failures ( of processor nodes or of communication links ) are possible fall under this domain.


if you apply binary search, you have $ $ \ log _ 2 ( n ) + o ( 1 ) $ $ many comparisons. if you apply ternary search, you have $ $ 2 \ cdot \ log _ 3 ( n ) + o ( 1 ) $ $ many comparisons, as in each step, you need to perform 2 comparisons to cut the search space into three parts. now if you do the math, you can observe that : $ $ 2 \ cdot \ log _ 3 ( n ) + o ( 1 ) = 2 \ cdot \ frac { \ log ( 2 ) } { \ log ( 3 ) } \ log _ 2 ( n ) + o ( 1 ) $ $ since we know that $ 2 \ cdot \ frac { \ log ( 2 ) } { \ log ( 3 ) } > 1 $, we actually get more comparisons with ternary search. by the way : $ n $ - ary search may make a lot of sense in case if comparisons are quite costly and can be parallelized, as then, parallel computers can be applied. note that argument can be generalized to $ n $ - ary search quite easily. you just need to show that the function $ f ( k ) = ( k - 1 ) \ cdot \ frac { \ log ( 2 ) } { \ log ( k ) } $ is strictly monotone increasing for integer values of $ k $.


the anode is the electrode where the oxidation reaction \ begin { align } \ ce { red - > ox + e - } \ end { align } takes place while the cathode is the electrode where the reduction reaction \ begin { align } \ ce { ox + e - - > red } \ end { align } takes place. that's how cathode and anode are defined. galvanic cell now, in a galvanic cell the reaction proceeds without an external potential helping it along. since at the anode you have the oxidation reaction which produces electrons you get a build - up of negative charge in the course of the reaction until electrochemical equilibrium is reached. thus the anode is negative. at the cathode, on the other hand, you have the reduction reaction which consumes electrons ( leaving behind positive ( metal ) ions at the electrode ) and thus leads to a build - up of positive charge in the course of the reaction until electrochemical equilibrium is reached. thus the cathode is positive. electrolytic cell in an electrolytic cell, you apply an external potential to enforce the reaction to go in the opposite direction. now the reasoning is reversed. at the negative electrode where you have produced a high electron potential via an external voltage source electrons are " pushed out " of the electrode, thereby reducing the oxidized species $ \ ce { ox } $, because the electron energy level inside the electrode ( fermi level ) is higher than the energy level of the lumo of $ \ ce { ox } $ and the electrons can lower their energy by occupying this orbital - you have very reactive electrons so to speak. so the negative electrode will be the one where the reduction reaction will take place and thus it's the cathode. at the positive electrode where you have produced a low electron potential via an external voltage source electrons are " sucked into " the electrode leaving behind the the reduced species $ \ ce { red } $ because the electron energy level inside the electrode ( fermi level ) is lower than the energy level of the homo of $ \ ce { red } $. so the positive electrode will be the one where the oxidation reaction will take place and thus it's the anode. a tale of electrons and waterfalls since there is some confusion concerning the principles on which an electrolysis works, i'll try a metaphor to explain it. electrons flow from a region of high potential to a region of low potential much like water falls down a waterfall or flows down an


inclined plane. the reason is the same : water and electrons can lower their energy this way. now the external voltage source acts like two big rivers connected to waterfalls : one at a high altitude that leads towards a waterfall - that would be the minus pole - and one at a low altitude that leads away from a waterfall - that would be the plus pole. the electrodes would be like the points of the river shortly before or after the waterfalls in this picture : the cathode is like the edge of a waterfall where the water drops down and the anode is like the point where the water drops into. ok, what happens at the electrolysis reaction? at the cathode, you have the high altitude situation. so the electrons flow to the " edge of their waterfall ". they want to " fall down " because behind them the river is pushing towards the edge exerting some kind of " pressure ". but where can they fall down to? the other electrode is separated from them by the solution and usually a diaphragm. but there are $ \ ce { ox } $ molecules that have empty states that lie energetically below that of the electrode. those empty states are like small ponds lying at a lower altitude where a little bit of the water from the river can fall into. so every time such an $ \ ce { ox } $ molecule comes near the electrode an electron takes the opportunity to jump to it and reduce it to $ \ ce { red } $. but that does not mean that the electrode is suddenly missing an electron because the river is replacing the " pushed out " electron immediately. and the voltage source ( the source of the river ) can't run dry of electrons because it gets its electrons from the power socket. now the anode : at the anode, you have the low altitude situation. so here the river lies lower than everything else. now you can imagine the homo - states of the $ \ ce { red } $ molecules as small barrier lakes lying at a higher altitude than our river. when a $ \ ce { red } $ molecule comes close to the electrode it is like someone opening the floodgates of the barrier lake's dam. the electrons flow from the homo into the electrode thus creating an $ \ ce { ox } $ molecule. but the electrons don't stay in the electrode, so to speak, they are carried away by the river. and since the river is such a vast entity ( lots of water ) and usually flows into an ocean, the little "


water " that is added to it doesn't change the river much. it stays the same, unaltered so that everytime a floodgate gets opened the water from the barrier lake will drop the same distance.


dataset will be a data frame. as i don't have forr. csv, i'll make up a small data frame for illustration : set. seed ( 1 ) dataset < - data. frame ( a = sample ( c ( na, 1 : 100 ), 1000, rep = true ), b = rnorm ( 1000 ) ) > head ( dataset ) a b 1 26 0. 07730312 2 37 - 0. 29686864 3 57 - 1. 18324224 4 91 0. 01129269 5 20 0. 99160104 6 90 1. 59396745 to get the number of cases, count the number of rows using nrow ( ) or nrow ( ) : > nrow ( dataset ) [ 1 ] 1000 > nrow ( dataset ) [ 1 ] 1000 to count the data after omitting the na, use the same tools, but wrap dataset in na. omit ( ) : > nrow ( na. omit ( dataset ) ) [ 1 ] 993 the difference between nrow ( ) and ncol ( ) and their lowercase variants ( ncol ( ) and nrow ( ) ) is that the lowercase versions will only work for objects that have dimensions ( arrays, matrices, data frames ). the uppercase versions will work with vectors, which are treated as if they were a 1 column matrix, and are robust if you end up subsetting your data such that r drops an empty dimension. alternatively, use complete. cases ( ) and sum it ( complete. cases ( ) returns a logical vector [ true or false ] indicating if any observations are na for any rows. > sum ( complete. cases ( dataset ) ) [ 1 ] 993


the difference in your timings seems to be due to the manual unrolling of the unit - stride fortran daxpy. the following timings are on a 2. 67 ghz xeon x5650, using the command. / test 1000000 10000 intel 11. 1 compilers fortran with manual unrolling : 8. 7 sec fortran w / o manual unrolling : 5. 8 sec c w / o manual unrolling : 5. 8 sec gnu 4. 1. 2 compilers fortran with manual unrolling : 8. 3 sec fortran w / o manual unrolling : 13. 5 sec c w / o manual unrolling : 13. 6 sec c with vector attributes : 5. 8 sec gnu 4. 4. 5 compilers fortran with manual unrolling : 8. 1 sec fortran w / o manual unrolling : 7. 4 sec c w / o manual unrolling : 8. 5 sec c with vector atrributes : 5. 8 sec conclusions manual unrolling helped the gnu 4. 1. 2 fortran compilers on this architecture, but hurts the newer version ( 4. 4. 5 ) and the intel fortran compiler. the gnu 4. 4. 5 c compiler is much more competitive with fortran than for version 4. 2. 1. vector intrinsics allow the gcc performance to match the intel compilers. time to test more complicated routines like dgemv and dgemm?


sorry i don't know opencv, and this is more a pre - processing step than a complete answer : first, you don't want an edge detector. an edge detector converts transitions ( like this dark - to - light ) : into ridges ( bright lines on dark ) like this : it performs a differentiation, in other words. but in your images, there is a light shining down from one direction, which shows us the relief of the 3d surface. we perceive this as lines and edges, because we're used to seeing things in 3d, but they aren't really, which is why edge detectors aren't working, and template matching won't work easily with rotated images ( a perfect match at 0 degrees rotation would actually cancel out completely at 180 degrees, because light and dark would line up with each other ). if the height of one of these mazy lines looks like this from the side : then the brightness function when illuminated from one side will look like this : this is what you see in your images. the facing surface becomes brighter and the trailing surface becomes darker. so you don't want to differentiate. you need to integrate the image along the direction of illumination, and it will give you the original height map of the surface ( approximately ). then it will be easier to match things, whether through hough transform or template matching or whatever. i'm not sure how to automate finding the direction of illumination. if it's the same for all your images, great. otherwise you'd have to find the biggest contrast line and assume the light is perpendicular to it or something. for my example, i rotated the image manually to what i thought was the right direction, with light coming from the left : you also need to remove all the low - frequency changes in the image, though, to highlight only the quickly - changing line - like features. to avoid ringing artifacts, i used 2d gaussian blur and then subtracted that from the original : the integration ( cumulative sum ) can runaway easily, which produces horizontal streaks. i removed these with another gaussian high - pass, but only in the horizontal direction this time : now the stomata are white ellipses all the way around, instead of white in some places and black in others. original : integrated : from pylab import * import image from scipy. ndimage import gaussian _ filter, gaussian _ filter1d filename ='rotated _ sample. jpg'i


= image. open ( filename ). convert ('l') i = asarray ( i ) # remove dc offset i = i - average ( i ) close ('all') figure ( ) imshow ( i ) gray ( ) show ( ) title ('original') # remove slowly - varying features sigma _ 2d = 2 i = i - gaussian _ filter ( i, sigma _ 2d ) figure ( ) imshow ( i ) title ('2d filtered with % s'% sigma _ 2d ) # integrate summed = cumsum ( i, 1 ) # remove slowly - changing streaks in horizontal direction sigma _ 1d = 5 output = summed - gaussian _ filter1d ( summed, sigma _ 1d, axis = 1 ) figure ( ) imshow ( output ) title ('1d filtered with % s'% sigma _ 1d ) the hough transform can be used to detect ridge ellipses like this, made of " edge pixels ", though it's really expensive in computation and memory, and they are not perfect ellipses so it would have to be a bit of a " sloppy " detector. i've never done it, but there are a lot of google results for " hough ellipse detection ". i'd say if you detect one ellipse inside the other, within a certain size search space, it should be counted as a stoma. also see : opencv : how to detect a ellipse in the binary image python and opencv. how do i detect all ( filled ) circles / round objects in an image? detection of coins ( and fit ellipses ) on an image


a linear function fixes the origin, whereas an affine function need not do so. an affine function is the composition of a linear function with a translation, so while the linear part fixes the origin, the translation can map it somewhere else. linear functions between vector spaces preserve the vector space structure ( so in particular they must fix the origin ). while affine functions don't preserve the origin, they do preserve some of the other geometry of the space, such as the collection of straight lines. if you choose bases for vector spaces $ v $ and $ w $ of dimensions $ m $ and $ n $ respectively, and consider functions $ f \ colon v \ to w $, then $ f $ is linear if $ f ( v ) = av $ for some $ n \ times m $ matrix $ a $ and $ f $ is affine if $ f ( v ) = av + b $ for some matrix $ a $ and vector $ b $, where coordinate representations are used with respect to the bases chosen.


i think that documentation for scientific software can be divided into three categories, all of which are necessary for full understanding. the easiest and most common is individual method documentation. there are many systems for this. you mention doxygen, python has pydoc, and in petsc we have our own package sowing which generates the following. however, for any piece of software which goes beyond a simple utility, you need a manual. this provides a high - level view of the purpose of the package, and how its different functionalities integrate to achieve this purpose. it helps a new user structure their code, often through the use of examples. in petsc, we just use latex for the manual, but the pyclaw package uses the sphinx framework which i am very impressed with. one thing that we have implemented in the sowing package that i find very useful is the link between example code and function documentation. for example, this example solves the bratu equation. notice how you can follow the links for any custom type or function call and get to the low - level documentation, and how those pages link back to examples using them. this is how i learn about new functionality which other people in the project contribute. a frequently overlooked part of documentation, i think, is developer documentation. it is not uncommon to publish a coding - style document, and instructions for interacting with the repository. however, it is very rare to explain the design decisions made before implementation. these decisions always involve tradeoffs, and the situation with respect to hardware and algorithms will necessarily change over time. without a discussion of the tradeoffs reviewed and rationale for particular design decisions, later programmers are left to recreate the entire process on their own. i think this is a major impediment to successful maintenance and improvement of old codes when the original developers are no longer in charge.


i am not a kineticist, and my quantum chemistry is long, long out of date, but what i was about to say was that i'd guess the reason the " effect " is " unsolved " is that it's not real. that is, it is not a property of a single reactant while disregarding its environment ( gas phase, solvent interactions ). then i saw that the two recent articles both were about solvation, so my comment is redundant ( and certainly only a partially / inadequately educated guess ). i'd also comment that comparing $ \ ce { ho - } $ with $ \ ce { hoo - } $ is apples and oranges. you should compare it with a species with an alpha atom which is electronegative but doesn't have a lone pair. if it doesn't really have a published dft model, then it might be good for an ms student to work on. i suspect answering it is like " curing cancer ", it doesn't have just one'reason ', rather the cures depend on the exact nature of the reaction ( including solvation ).


what ’ s the proper soldering iron temperature for standard. 031 " 60 / 40 solder? there is no proper soldering iron temperature just for a given type of solder - the iron temperature should be set for both the component and the solder. when soldering surface mount components, a small tip and 600f ( 315c ) should be sufficient to quickly solder the joint well without overheating the component. when soldering through hole components, 700f ( 370c ) is useful to pump more heat into the wire and plated hole to solder it quickly. a negative capacitor lead to a heatsinking solid pour ground plane is going to need a big fat tip at a much higher temperature. however, i don't micromanage my soldering temperature, and simply keep mine at 700f ( 370c ). i'll change the tips according to what i'm soldering, and the tip size really ends up determining how much heat gets into the joint in a given period of contact. i think you'll find that very few soldering jobs will really require you to change your tip temperature. keep in mind that the ideal situation is that the soldering iron heats up the joint enough that the joint melts the solder - not the iron. so the iron is expected to be hotter than the melting point of the solder so that the entire joint comes up to the melting point of the solder quickly. the more quickly you bring the joint temperature up and solder it, the less time the soldering iron is on the joint, and thus the less heat gets transferred to the component. it's not a big deal for many passive or small components, but it turns out that overall a higher tip temperature results in faster soldering and less likely damage to the component being soldered. so if you do use higher tip temperatures, don't leave them on components any longer than necessary. apply the iron, apply the solder, and remove both - it should take just a second or maybe two for surface mount, and 1 - 3 seconds for a through hole part. please note that i'm talking about prototyping, hobbyist, and one - off projects. if you are planning on doing final assembly with the iron, repair work for critical projects, etc, then you'll need to consider what you're doing more carefully than this general rule of thumb.


samtools has a subsampling option : - s float : integer part is used to seed the random number generator [ 0 ]. part after the decimal point sets the fraction of templates / pairs to subsample [ no subsampling ] samtools view - bs 42. 1 in. bam > subsampled. bam will subsample 10 percent mapped reads with 42 as the seed for the random number generator.


the laplace and fourier transforms are continuous ( integral ) transforms of continuous functions. the laplace transform maps a function \ $ f ( t ) \ $ to a function \ $ f ( s ) \ $ of the complex variable s, where \ $ s = \ sigma + j \ omega \ $. since the derivative \ $ \ dot f ( t ) = \ frac { df ( t ) } { dt } \ $ maps to \ $ sf ( s ) \ $, the laplace transform of a linear differential equation is an algebraic equation. thus, the laplace transform is useful for, among other things, solving linear differential equations. if we set the real part of the complex variable s to zero, \ $ \ sigma = 0 \ $, the result is the fourier transform \ $ f ( j \ omega ) \ $ which is essentially the frequency domain representation of \ $ f ( t ) \ $ ( note that this is true only if for that value of \ $ \ sigma \ $ the formula to obtain the laplace transform of \ $ f ( t ) \ $ exists, i. e., it does not go to infinity ). the z transform is essentially a discrete version of the laplace transform and, thus, can be useful in solving difference equations, the discrete version of differential equations. the z transform maps a sequence \ $ f [ n ] \ $ to a continuous function \ $ f ( z ) \ $ of the complex variable \ $ z = re ^ { j \ omega } \ $. if we set the magnitude of z to unity, \ $ r = 1 \ $, the result is the discrete time fourier transform ( dtft ) \ $ f ( j \ omega ) \ $ which is essentially the frequency domain representation of \ $ f [ n ] \ $.


a guy is flying in a hot air balloon and he's lost. so he lowers himself over a field and shouts to a guy on the ground : " can you tell me where i am, and which way i'm headed? " " sure! you're at 43 degrees, 12 minutes, 21. 2 seconds north ; 123 degrees, 8 minutes, 12. 8 seconds west. you're at 212 meters above sea level. right now, you're hovering, but on your way in here you were at a speed of 1. 83 meters per second at 1. 929 radians " " thanks! by the way, are you a statistician? " " i am! but how did you know? " " everything you've told me is completely accurate ; you gave me more detail than i needed, and you told me in such a way that it's no use to me at all! " " dang! by the way, are you a principal investigator? " " geeze! how'd you know that???? " " you don't know where you are, you don't know where you're going. you got where you are by blowing hot air, you start asking questions after you get into trouble, and you're in exactly the same spot you were a few minutes ago, but now, somehow, it's my fault!


i've decided to tackle this question in a somewhat different manner. instead of giving the chemical intuition behind it, i wanted to check for myself if the mathematics actually work out. as far as i understand, this isn't done often, so that's why i wanted to try it, even though it may not make the clearest answer. it turns out to be a bit complicated, and i haven't done much math in a while, so i'm kinda rusty. hopefully, everything is correct. i would love to have someone check my results. my approach here is to explicitly find the equation of a general titration curve and figure out from that why the ph varies quickly near the equivalence point. for simplicity, i shall consider the titration to be between a monoprotic acid and base. explicitly, we have the following equilibria in solution $ $ \ ce { ha < = > h ^ + + a ^ - } \ \ \ → \ \ \ k _ \ text { a } = \ ce { \ frac { [ h ^ + ] [ a ^ - ] } { [ ha ] } } $ $ $ $ \ ce { boh < = > b ^ + + oh ^ - } \ \ \ → \ \ \ k _ \ text { b } = \ ce { \ frac { [ oh ^ - ] [ b ^ + ] } { [ boh ] } } $ $ $ $ \ ce { h2o < = > h ^ + + oh ^ - } \ \ \ → \ \ \ k _ \ text { w } = \ ce { [ h ^ + ] [ oh ^ - ] } $ $ let us imagine adding two solutions, one of the acid $ \ ce { ha } $ with volume $ v _ \ text { a } $ and concentration $ c _ \ text { a } $, and another of the base $ \ ce { boh } $ with volume $ v _ \ text { b } $ and concentration $ c _ \ text { b } $. notice that after mixing the solutions, the number of moles of species containing $ \ ce { a } $ ( $ \ ce { ha } $ or $ \ ce { a ^ - } $ ) is simply $ n _ \ text { a } = c _ \ text { a } v _ \ text { a } $, while the number of moles of species containing $ \ ce { b } $ ( $ \ ce


{ boh } $ or $ \ ce { b ^ + } $ ) is $ n _ \ text { b } = c _ \ text { b } v _ \ text { b } $. notice that at the equivalence point, $ n _ \ text { a } = n _ \ text { b } $ and therefore $ c _ \ text { a } v _ \ text { a } = c _ \ text { b } v _ \ text { b } $ ; this will be important later. we will assume that volumes are additive ( total volume $ v _ \ text { t } = v _ \ text { a } + v _ \ text { b } $ ), which is close to true for relatively dilute solutions. in search of an equation to solve the problem of finding the final equilibrium after adding the solutions, we write out the charge balance and matter balance equations : charge balance : $ \ ce { [ h ^ + ] + [ b ^ + ] = [ a ^ - ] + [ oh ^ - ] } $ matter balance for $ \ ce { a } $ : $ \ displaystyle \ ce { [ ha ] + [ a ^ - ] } = \ frac { c _ \ text { a } v _ \ text { a } } { v _ \ text { a } + v _ \ text { b } } $ matter balance for $ \ ce { b } $ : $ \ displaystyle \ ce { [ boh ] + [ b ^ + ] } = \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } $ a titration curve is given by the ph on the $ y $ - axis and the volume of added acid / base on the $ x $ - axis. so what we need is to find an equation where the only variables are $ \ ce { [ h ^ + ] } $ and $ v _ \ text { a } $ or $ v _ \ text { b } $. by manipulating the dissociation constant equations and the mass balance equations, we can find the following : $ $ \ ce { [ ha ] } = \ frac { \ ce { [ h ^ + ] [ a ^ - ] } } { k _ \ text { a } } $ $ $ $ \ ce { [ boh ] } = \ frac { \ ce { [ b ^ + ] }


k _ \ text { w } } { k _ \ text { b } \ ce { [ h ^ + ] } } $ $ $ $ \ ce { [ a ^ - ] } = \ frac { c _ \ text { a } v _ \ text { a } } { v _ \ text { a } + v _ \ text { b } } \ left ( \ frac { k _ \ text { a } } { k _ \ text { a } + \ ce { [ h ^ + ] } } \ right ) $ $ $ $ \ ce { [ b ^ + ] } = \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } \ left ( \ frac { k _ \ text { b } \ ce { [ h ^ + ] } } { k _ \ text { b } \ ce { [ h ^ + ] } + k _ \ text { w } } \ right ) $ $ replacing those identities in the charge balance equation, after a decent bit of algebra, yields : $ $ \ ce { [ h ^ + ] ^ 4 } + \ left ( k _ \ text { a } + \ frac { k _ \ text { w } } { k _ \ text { b } } + \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } \ right ) \ ce { [ h ^ + ] ^ 3 } + \ left ( \ frac { k _ \ text { a } } { k _ \ text { b } } k _ \ text { w } + \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } k _ \ text { a } - \ frac { c _ \ text { a } v _ \ text { a } } { v _ \ text { a } + v _ \ text { b } } k _ \ text { a } - k _ \ text { w } \ right ) \ ce { [ h ^ + ] ^ 2 } - \ left ( k _ \ text { a } k _ \ text { w } + \ frac { c _ \ text { a } v _ \ text { a }


} { v _ \ text { a } + v _ \ text { b } } \ frac { k _ \ text { a } } { k _ \ text { b } } k _ \ text { w } + \ frac { k ^ 2 _ \ text { w } } { k _ \ text { b } } \ right ) \ ce { [ h ^ + ] } - \ frac { k _ \ text { a } } { k _ \ text { b } } k ^ 2 _ \ text { w } = 0 $ $ now, this equation sure looks intimidating, but it is very interesting. for one, this single equation will exactly solve any equilibrium problem involving the mixture of any monoprotic acid and any monoprotic base, in any concentration ( as long as they're not much higher than about $ 1 ~ \ mathrm { \ small m } $ ) and any volume. though it doesn't seem to be possible to separate the variables $ \ ce { [ h ^ + ] } $ and $ v _ \ text { a } $ or $ v _ \ text { b } $, the graph of this equation represents any titration curve ( as long as it obeys the previous considerations ). though in its full form it is quite daunting, we can obtain some simpler versions. for example, consider that the mixture is of a weak acid and a strong base. this means that $ k _ \ text { b } \ gg 1 $, and so every term containing $ k _ \ text { b } $ in the denominator is approximately zero and gets cancelled out. the equation then becomes : weak acid and strong base : $ $ \ ce { [ h ^ + ] ^ 3 } + \ left ( k _ \ text { a } + \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } \ right ) \ ce { [ h ^ + ] ^ 2 } + \ left ( \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ ce { a } + v _ \ ce { b } } k _ \ ce { a } - \ frac { c _ \ ce { a } v _ \ ce { a } } { v _ \ ce { a } + v _ \ ce { b } } k _ \


ce { a } - k _ \ ce { w } \ right ) \ ce { [ h ^ + ] } - k _ \ ce { a } k _ \ ce { w } = 0 $ $ for a strong acid and weak base ( $ k _ \ text { a } \ gg 1 $ ), you can divide both sides of the equation by $ k _ \ text { a } $, and now all terms with $ k _ \ text { a } $ in the denominator get cancelled out, leaving : strong acid and weak base : $ $ \ ce { [ h ^ + ] ^ 3 } + \ left ( \ frac { k _ \ ce { w } } { k _ \ ce { b } } + \ frac { c _ \ ce { b } v _ \ ce { b } } { v _ \ ce { a } + v _ \ ce { b } } - \ frac { c _ \ ce { a } v _ \ ce { a } } { v _ \ ce { a } + v _ \ ce { b } } \ right ) \ ce { [ h ^ + ] ^ 2 } - \ left ( k _ \ ce { w } + \ frac { c _ \ text { a } v _ \ ce { a } } { v _ \ ce { a } + v _ \ ce { b } } \ frac { k _ \ ce { w } } { k _ \ ce { b } } \ right ) \ ce { [ h ^ + ] } - \ frac { k ^ 2 _ \ ce { w } } { k _ \ ce { b } } = 0 $ $ the simplest case happens when adding a strong acid to a strong base ( $ k _ \ ce { a } \ gg 1 $ and $ k _ \ ce { b } \ gg 1 $ ), in which case all terms containing either in the denominator get cancelled out. the result is simply : strong acid and strong base : $ $ \ ce { [ h ^ + ] ^ 2 } + \ left ( \ frac { c _ \ text { b } v _ \ text { b } } { v _ \ text { a } + v _ \ text { b } } - \ frac { c _ \ text { a } v _ \ text { a } } { v _ \ text { a } + v _ \ text { b } } \


right ) \ ce { [ h ^ + ] } - k _ \ ce { w } = 0 $ $ it would be enlightening to draw some example graphs for each equation, but wolfram alpha only seems to be able to handle the last one, as the others require more than the standard computation time to display. still, considering the titration of $ 1 ~ \ text { l } $ of a $ 1 ~ \ ce { \ small m } $ solution of a strong acid with a $ 1 ~ \ ce { \ small m } $ solution of a strong base, you get this graph. the $ x $ - axis is the volume of base added, in litres, while the $ y $ - axis is the ph. notice that the graph is exactly as what you'll find in a textbook! now what? with the equations figured out, let's study how they work. we want to know why the ph changes quickly near the equivalence point, so a good idea is to analyze the derivative of the equation and figure out where they have a very positive or very negative value, indicating a region where $ \ ce { [ h ^ + ] } $ changes quickly with a slight addition of an acid / base. suppose we want to study the titration of an acid with a base. what we need then is the derivative $ \ displaystyle \ frac { \ ce { d [ h ^ + ] } } { \ ce { d } v _ \ ce { b } } $. we will obtain this by implicit differentiation of both sides of the equations by $ \ displaystyle \ frac { \ ce { d } } { \ ce { d } v _ \ ce { b } } $. starting with the easiest case, the mixture of a strong acid and strong base, we obtain : $ $ \ frac { \ ce { d [ h ^ + ] } } { \ ce { d } v _ \ ce { b } } = \ frac { k _ \ ce { w } - c _ \ ce { b } \ ce { [ h ^ + ] - [ h ^ + ] ^ 2 } } { 2 ( v _ \ ce { a } + v _ \ ce { b } \ left ) \ ce { [ h ^ + ] } + ( c _ \ ce { b } v _ \ ce { b } - c _ \ ce { a } v _ \ ce { a } \ right ) } $ $ once again a


complicated looking fraction, but with very interesting properties. the numerator is not too important, it's the denominator where the magic happens. notice that we have a sum of two terms ( $ 2 ( v _ \ ce { a } + v _ \ ce { b } ) \ ce { [ h ^ + ] } $ and $ ( c _ \ ce { b } v _ \ ce { b } - c _ \ ce { a } v _ \ ce { a } ) $ ). the lower this sum is, the higher $ \ displaystyle \ frac { \ mathrm { d } \ ce { [ h ^ + ] } } { \ mathrm { d } v _ \ ce { b } } $ is and the quicker the ph will change with a small addition of the base. notice also that, if the solutions aren't very dilute, then the second term quickly dominates the denominator because while adding base, the value of $ [ h ^ + ] $ will become quite small compared to $ c _ \ ce { a } $ and $ c _ \ ce { b } $. now we have a very interesting situation ; a fraction where the major component of the denominator has a subtraction. here's an example of how this sort of function behaves. when the subtraction ends up giving a result close to zero, the function explodes. this means that the speed at which $ \ ce { [ h ^ + ] } $ changes becomes very sensitive to small variations of $ v _ \ ce { b } $ near the critical region. and where does this critical region happen? well, close to the region where $ c _ \ ce { b } v _ \ ce { b } - c _ \ ce { a } v _ \ ce { a } $ is zero. if you remember the start of the answer, this is the equivalence point!. so there, this proves mathematically that the speed at which the ph changes is maximum at the equivalence point. this was only the simplest case though. let's try something a little harder. taking the titration equation for a weak acid with strong base, and implicitly differentiating both sides by $ \ displaystyle \ frac { \ ce { d } } { \ ce { d } v _ \ ce { b } } $ again, we get the significantly more fearsome : $ $ \ displaystyle \ frac { \ ce { d [ h


^ + ] } } { \ ce { d } v _ \ ce { b } } = \ frac { - \ frac { v _ \ ce { a } } { ( v _ \ ce { a } + v _ \ ce { b } ) ^ 2 } \ ce { [ h ^ + ] } ( c _ \ ce { b } \ ce { [ h ^ + ] } - c _ \ ce { b } k _ \ ce { a } + c _ \ ce { a } k _ \ ce { a } ) } { 3 \ ce { [ h ^ + ] ^ 2 + 2 [ h ^ + ] } \ left ( k _ \ ce { a } + \ frac { c _ \ ce { b } v _ \ ce { b } } { v _ \ ce { a } + v _ \ ce { b } } \ right ) + \ frac { k _ \ ce { a } } { v _ \ ce { a } + v _ \ ce { b } } ( c _ \ ce { b } v _ \ ce { b } - c _ \ ce { a } v _ \ ce { a } ) - k _ \ ce { w } } $ $ once again, the term that dominates the behaviour of the complicated denominator is the part containing $ c _ \ ce { b } v _ \ ce { b } - c _ \ ce { a } v _ \ ce { a } $, and once again the derivative explodes at the equivalence point.


here is a 97 - line example of solving a simple multivariate pde using finite difference methods, contributed by prof. david ketcheson, from the py4sci repository i maintain. for more complicated problems where you need to handle shocks or conservation in a finite - volume discretization, i recommend looking at pyclaw, a software package that i help develop. " " " pattern formation code solves the pair of pdes : u _ t = d _ 1 \ nabla ^ 2 u + f ( u, v ) v _ t = d _ 2 \ nabla ^ 2 v + g ( u, v ) " " " import matplotlib matplotlib. use ('tkagg') import numpy as np import matplotlib. pyplot as plt from scipy. sparse import spdiags, linalg, eye from time import sleep # parameter values du = 0. 500 ; dv = 1 ; delta = 0. 0045 ; tau1 = 0. 02 ; tau2 = 0. 2 ; alpha = 0. 899 ; beta = - 0. 91 ; gamma = - alpha ; # delta = 0. 0045 ; tau1 = 0. 02 ; tau2 = 0. 2 ; alpha = 1. 9 ; beta = - 0. 91 ; gamma = - alpha ; # delta = 0. 0045 ; tau1 = 2. 02 ; tau2 = 0. ; alpha = 2. 0 ; beta = - 0. 91 ; gamma = - alpha ; # delta = 0. 0021 ; tau1 = 3. 5 ; tau2 = 0 ; alpha = 0. 899 ; beta = - 0. 91 ; gamma = - alpha ; # delta = 0. 0045 ; tau1 = 0. 02 ; tau2 = 0. 2 ; alpha = 1. 9 ; beta = - 0. 85 ; gamma = - alpha ; # delta = 0. 0001 ; tau1 = 0. 02 ; tau2 = 0. 2 ; alpha = 0. 899 ; beta = - 0. 91 ; gamma = - alpha ; # delta = 0. 0005 ; tau1 = 2. 02 ; tau2 = 0. ; alpha = 2. 0 ; beta = - 0. 91 ; gamma = - alpha ; nx = 150 ; # define the reaction functions def f ( u, v ) : return alpha * u * ( 1 - tau1 *


v * * 2 ) + v * ( 1 - tau2 * u ) ; def g ( u, v ) : return beta * v * ( 1 + alpha * tau1 / beta * u * v ) + u * ( gamma + tau2 * v ) ; def five _ pt _ laplacian ( m, a, b ) : " " " construct a matrix that applies the 5 - point laplacian discretization " " " e = np. ones ( m * * 2 ) e2 = ( [ 0 ] + [ 1 ] * ( m - 1 ) ) * m h = ( b - a ) / ( m + 1 ) a = np. diag ( - 4 * e, 0 ) + np. diag ( e2 [ 1 : ], - 1 ) + np. diag ( e2 [ 1 : ], 1 ) + np. diag ( e [ m : ], m ) + np. diag ( e [ m : ], - m ) a / = h * * 2 return a def five _ pt _ laplacian _ sparse ( m, a, b ) : " " " construct a sparse matrix that applies the 5 - point laplacian discretization " " " e = np. ones ( m * * 2 ) e2 = ( [ 1 ] * ( m - 1 ) + [ 0 ] ) * m e3 = ( [ 0 ] + [ 1 ] * ( m - 1 ) ) * m h = ( b - a ) / ( m + 1 ) a = spdiags ( [ - 4 * e, e2, e3, e, e ], [ 0, - 1, 1, - m, m ], m * * 2, m * * 2 ) a / = h * * 2 return a # set up the grid a = - 1. ; b = 1. m = 100 ; h = ( b - a ) / m ; x = np. linspace ( - 1, 1, m ) y = np. linspace ( - 1, 1, m ) y, x = np. meshgrid ( y, x ) # initial data u = np. random. randn ( m, m ) / 2. ; v = np. random. randn ( m, m ) / 2. ; plt. hold ( false ) plt. pcolormesh ( x, y, u ) plt.


colorbar ; plt. axis ('image') ; plt. draw ( ) u = u. reshape ( - 1 ) v = v. reshape ( - 1 ) a = five _ pt _ laplacian _ sparse ( m, - 1., 1. ) ; ii = eye ( m * m, m * m ) t = 0. dt = h / delta / 5. ; plt. ion ( ) # now step forward in time for k in range ( 120 ) : # simple ( 1st - order ) operator splitting : u = linalg. spsolve ( ii - dt * delta * du * a, u ) v = linalg. spsolve ( ii - dt * delta * dv * a, v ) unew = u + dt * f ( u, v ) ; v = v + dt * g ( u, v ) ; u = unew ; t = t + dt ; # plot every 3rd frame if k / 3 = = float ( k ) / 3 : u = u. reshape ( ( m, m ) ) plt. pcolormesh ( x, y, u ) plt. colorbar plt. axis ('image') plt. title ( str ( t ) ) plt. draw ( ) plt. ioff ( )


summary spi is faster. i2c is more complex and not as easy to use if your microcontroller doesn't have an i2c controller. i2c only requires 2 lines. i2c is a bus system with bidirectional data on the sda line. spi is a point - to - point connection with data in and data out on separate lines ( mosi and miso ). essentially spi consists of a pair of shift registers, where you clock data in to one shift register while you clock data out of the other. usually data is written in bytes by having each time 8 clock pulses in succession, but that's not an spi requirement. you can also have word lengths of 16 bit or even 13 bit, if you like. while in i2c synchronization is done by the start sequence in spi it's done by ss going high ( ss is active low ). you decide yourself after how many clock pulses this is. if you use 13 bit words the ss will latch the last clocked in bits after 13 clock pulses. since the bidirectional data is on two separate lines it's easy to interface. spi in standard mode needs at least four lines : sclk ( serial clock ), mosi ( master out slave in ), miso ( master in slave out ) and ss ( slave select ). in bideroctional mode needs at least three lines : sclk ( serial clock ), mimo ( master in master out ) which is one of the mosi or miso lines and ss ( slave select ). in systems with more than one slave you need a ss line for each slave, so that for \ $ n \ $ slaves you have \ $ n + 3 \ $ lines in standard mode and \ $ n + 2 \ $ lines in bidirectional mode. if you don't want that, in standard mode you can daisy - chain the slaves by connecting the mosi signal of one slave to the miso of the next. this will slow down communication since you have to cycle through all slaves data. like tcrosley says spi can operate at a much higher frequency than i2c. i2c is a bit more complex. since it's a bus you need a way to address devices. your communication starts with a unique start sequence : the data line ( sda ) is pulled low while the clock ( scl ) is high, for the rest of the


communication data is only allowed to change when the clock is low. this start sequence synchronizes each communication. since the communication includes the addressing only two lines are required for any number of devices ( up to 127 ). edit it's obvious that the data line is bidirectional, but it's worth noting that this is also true for the clock line. slaves may stretch the clock to control bus speed. this makes i2c less convenient for level - shifting or buffering. ( spi lines in standard mode are all unidirectional. ) after each byte ( address or data ) is sent the receiver has to acknowledge the receipt by placing an acknowledge pulse on sda. if your microcontroller has an i2c interface this will automatically be taken care of. you can still bit - bang it if your microcontroller doesn't support it, but you'll have to switch the i / o pin from output to input for each acknowledge or read data, unless you use an i / o pin for reading and one for writing. at 400khz standard i2c is much slower than spi. there are high - speed i2c devices which operate at 1mhz, still much slower than 20mhz spi.


arbitrary record access in constant time to get a random record in constant time, it is sufficient to get an arbitrary record in constant time. i have two solutions here : one with tabix and one with grabix. i think the grabix solution is more elegant, but i am keeping the tabix solution below because tabix is a more mature tool than grabix. thanks to user172818 for suggesting grabix. update this answer previously stated that tabix and grabix perform lookups in log ( n ) time. after taking a closer look at the grabix source code and the tabix paper i am now convinced that lookups are independent of n in complexity. however, both tools use an index that scales in size proportionally to n. so, the loading of the index is order n. however, if we consider the loading of the index as "... a single limited transformation of the data to another file format... ", then i think this answer is still a valid one. if more than one record is to be retrieved, then the index needs to be stored in memory, perhaps with a framework such as pysam or htslib. using grabix compress with bgzip. index the file and perform lookups with grabix in bash : gzip - dc input. fastq. gz | bgzip - c > output. fastq. gz grabix index output. fastq. gz # retrieve 5 - th record ( 1 - based ) in log ( n ) time # requires some math to convert indices ( 4 * 4 + 1, 4 * 4 + 4 ) = ( 17, 20 ) grabix grab output. fastq. gz 17 20 # count the number of records for part two of this question export n _ lines = $ ( gzip - dc output. fastq. gz | wc - l ) using tabix the tabix code is more complicated and relies on the iffy assumption that \ t is an acceptable character for replacement of \ n in a fastq record. if you are happy with a file format that is close to but not exactly fastq, then you could do the following : paste each record into a single line. add a dummy chromosome and line number as the first and second column. compress with bgzip. index the file and perform lookups with tabix note that we need to remove leading spaces introduced by nl and we need to introduce a dummy chromosome column to


keep tabix happy : gzip - dc input. fastq. gz | paste - - - - | nl | sed's / ^ * / /'| sed's / ^ / dummy \ t /'| bgzip - c > output. fastq. gz tabix - s 1 - b 2 - e 2 output. fastq. gz # now retrieve the 5th record ( 1 - based ) in log ( n ) time tabix output. fastq. gz dummy : 5 - 5 # this command will retrieve the 5th record and convert it record back into fastq format tabix output. fastq. gz dummy : 5 - 5 | perl - pe's / ^ dummy \ t \ d + \ t / /'| tr'\ t'' \ n'# count the number of records for part two of this question export n _ records = $ ( gzip - dc output. fastq. gz | wc - l ) random record in constant time now that we have a way of retrieving an arbitrary record in log ( n ) time, retrieving a random record is simply a matter of getting a good random number generator and sampling. here is some example code to do this in python : using grabix # random _ read. py import os import random n _ records = int ( os. environ [ " n _ lines " ] ) / / 4 rand _ record _ start = random. randrange ( 0, n _ records ) * 4 + 1 rand _ record _ end = rand _ record _ start + 3 os. system ( " grabix grab output. fastq. gz { 0 } { 1 } ". format ( rand _ record _ start, rand _ record _ end ) ) using tabix # random _ read. py import os import random n _ records = int ( os. environ [ " n _ records " ] ) rand _ record _ index = random. randrange ( 0, n _ records ) + 1 # super ugly, but works... os. system ( " tabix output. fastq. gz dummy : { 0 } - { 0 } | perl - pe's / ^ dummy \ t \ d + \ t / /'| tr'\ t'' \ n'". format ( rand _ record _ index ) ) and this works for me : python3. 5 random


_ read. py disclaimer please note that os. system calls a system shell and is vulnerable to shell injection vulnerabilities. if you are writing production code, then you probably want to take extra precautions. thanks to chris _ rands for raising this issue.


check into generatingfunctionology by herbert wilf. from the linked ( author's ) site, the second edition is available for downloading as a pdf. there is also a link to the third edition, available for purchase. it's a very helpful, useful, readable, fun, ( and short! ) book that a student could conceivably cover over winter break. another promising book by john conway ( et. al. ) is the symmetries of things, which may very well be of interest to students. one additional suggestion, as it is a classic well worth being placed on any serious student's bookshelf : how to solve it by george polya.


this answer is intended to clear up some misconceptions about resonance which have come up many times on this site. resonance is a part of valence bond theory which is used to describe delocalised electron systems in terms of contributing structures, each only involving 2 - centre - 2 - electron bonds. it is a concept that is very often taught badly and misinterpreted by students. the usual explanation is that it is as if the molecule is flipping back and forth between different structures very rapidly and that what is observed is an average of these structures. this is wrong! ( there are molecules that do this ( e. g bullvalene ), but the rapidly interconverting structures are not called resonance forms or resonance structures. ) individual resonance structures do not exist on their own. they are not in some sort of rapid equilibrium. there is only a single structure for a molecule such as benzene, which can be described by resonance. the difference between an equilibrium situation and a resonance situation can be seen on a potential energy diagram. this diagram shows two possible structures of the 2 - norbornyl cation. structure ( a ) shows the single delocalised structure, described by resonance whereas structures ( b ) show the equilibrium option, with the delocalised structure ( a ) as a transition state. the key point is that resonance hybrids are a single potential energy minimum, whereas equilibrating structures are two energy minima separated by a barrier. in 2013 an x - ray diffraction structure was finally obtained and the correct structure was shown to be ( a ). resonance describes delocalised bonding in terms of contributing structures that give some of their character to the single overall structure. these structures do not have to be equally weighted in their contribution. for example, amides can be described by the following resonance structures : the left structure is the major contributor but the right structure also contributes and so the structure of an amide has some double bond character in the c - n bond ( ie. the bond order is > 1 ) and less double bond character in the c - o bond ( bond order < 2 ). the alternative to valence bond theory and the resonance description of molecules is molecular orbital theory. this explains delocalised bonding as electrons occupying molecular orbitals which extend over more than two atoms.


filtfilt is zero - phase filtering, which doesn't shift the signal as it filters. since the phase is zero at all frequencies, it is also linear - phase. filtering backwards in time requires you to predict the future, so it can't be used in " online " real - life applications, only for offline processing of recordings of signals. lfilter is causal forward - in - time filtering only, similar to a real - life electronic filter. it can't be zero - phase. it can be linear - phase ( symmetrical fir ), but usually isn't. usually it adds different amounts of delay at different frequencies. an example and image should make it obvious. although the magnitude of the frequency response of the filters is identical ( top left and top right ), the zero - phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way : from _ _ future _ _ import division, print _ function import numpy as np from numpy. random import randn from numpy. fft import rfft from scipy import signal import matplotlib. pyplot as plt b, a = signal. butter ( 4, 0. 03, analog = false ) # show that frequency response is the same impulse = np. zeros ( 1000 ) impulse [ 500 ] = 1 # applies filter forward and backward in time imp _ ff = signal. filtfilt ( b, a, impulse ) # applies filter forward in time twice ( for same frequency response ) imp _ lf = signal. lfilter ( b, a, signal. lfilter ( b, a, impulse ) ) plt. subplot ( 2, 2, 1 ) plt. semilogx ( 20 * np. log10 ( np. abs ( rfft ( imp _ lf ) ) ) ) plt. ylim ( - 100, 20 ) plt. grid ( true, which ='both') plt. title ('lfilter') plt. subplot ( 2, 2, 2 ) plt. semilogx ( 20 * np. log10 ( np. abs ( rfft ( imp _ ff ) ) ) ) plt. ylim ( - 100, 20 ) plt. grid ( true, which ='both') plt. title ('filtfilt') sig =


np. cumsum ( randn ( 800 ) ) # brownian noise sig _ ff = signal. filtfilt ( b, a, sig ) sig _ lf = signal. lfilter ( b, a, signal. lfilter ( b, a, sig ) ) plt. subplot ( 2, 1, 2 ) plt. plot ( sig, color ='silver ', label ='original') plt. plot ( sig _ ff, color ='# 3465a4 ', label ='filtfilt') plt. plot ( sig _ lf, color ='# cc0000 ', label ='lfilter') plt. grid ( true, which ='both') plt. legend ( loc = " best " )


for fastq : seqtk fqchk in. fq | head - 2 it gives you percentage of " n " bases, not the exact count, though. for fasta : seqtk comp in. fa | awk'{ x + = $ 9 } end { print x }'this command line also works with fastq, but it will be slower as awk is slow. edit : ok, based on @ bach's reminder, here we go ( you need kseq. h to compile ) : / / to compile : gcc - o2 - o count - n this - prog. c - lz # include < zlib. h > # include < stdio. h > # include < stdint. h > # include " kseq. h " kseq _ init ( gzfile, gzread ) unsigned char dna5tbl [ 256 ] = { 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,


4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 } ; int main ( int argc, char * argv [ ] ) { long i, n _ n = 0, n _ acgt = 0, n _ gap = 0 ; gzfile fp ; kseq _ t * seq ; if ( argc = = 1 ) { fprintf ( stderr, " usage : count - n < in. fa > \ n " ) ; return 1 ; } if ( ( fp = gzopen ( argv [ 1 ], " r " ) ) = = 0 ) { fprintf ( stderr, " error : fail to open the input file \ n " ) ; return 1 ; } seq = kseq _ init ( fp ) ; while ( kseq _ read ( seq ) > = 0 ) { for ( i = 0 ; i < seq - > seq. l ; + + i ) { int c = dna5tbl [ ( unsigned char ) seq - > seq. s [ i ] ] ; if ( c < 4 ) + + n _ acgt ; else if ( c = = 4 ) + + n _ n ; else + + n _ gap ; } } kseq _ destroy ( seq ) ; gzclose ( fp ) ; printf ( " % ld \ t % ld \ t % ld \ n ", n _ acgt, n _ n, n _ gap ) ; return


0 ; } it works for both fasta / q and gzip'ed fasta / q. the following uses seqan : # include < seqan / seq _ io. h > using namespace seqan ; int main ( int argc, char * argv [ ] ) { if ( argc = = 1 ) { std : : cerr < < " usage : count - n < in. fastq > " < < std : : endl ; return 1 ; } std : : ios : : sync _ with _ stdio ( false ) ; charstring id ; dna5string seq ; seqfilein seqfilein ( argv [ 1 ] ) ; long i, n _ n = 0, n _ acgt = 0 ; while (! atend ( seqfilein ) ) { readrecord ( id, seq, seqfilein ) ; for ( i = beginposition ( seq ) ; i < endposition ( seq ) ; + + i ) if ( seq [ i ] < 4 ) + + n _ acgt ; else + + n _ n ; } std : : cout < < n _ acgt < <'\ t'< < n _ n < < std : : endl ; return 0 ; } on a fastq with 4 - million 150bp reads : the c version : ~ 0. 74 sec the c + + version : ~ 2. 15 sec an older c version without a lookup table ( see the previous edit ) : ~ 2. 65 sec


according to current nomenclature rules, $ \ ce { h3n } $ would be correct and acceptable. however some chemical formulas, like $ \ ce { nh3 } $ for ammonia, that were in use long before the rules came out, are still accepted today.


joblib does what you want. the basic usage pattern is : from joblib import parallel, delayed def myfun ( arg ) : do _ stuff return result results = parallel ( n _ jobs = - 1, verbose = verbosity _ level, backend = " threading " ) ( map ( delayed ( myfun ), arg _ instances ) ) where arg _ instances is list of values for which myfun is computed in parallel. the main restriction is that myfun must be a toplevel function. the backend parameter can be either " threading " or " multiprocessing ". you can pass additional common parameters to the parallelized function. the body of myfun can also refer to initialized global variables, the values which will be available to the children. args and results can be pretty much anything with the threading backend but results need to be serializable with the multiprocessing backend. dask also offers similar functionality. it might be preferable if you are working with out of core data or you are trying to parallelize more complex computations.


to quote from the answer to “ traversals from the root in avl trees and red black trees ” question for some kinds of binary search trees, including red - black trees but not avl trees, the " fixes " to the tree can fairly easily be predicted on the way down and performed during a single top - down pass, making the second pass unnecessary. such insertion algorithms are typically implemented with a loop rather than recursion, and often run slightly faster in practice than their two - pass counterparts. so a redblack tree insert can be implemented without recursion, on some cpus recursion is very expensive if you overrun the function call cache ( e. g sparc due to is use of register window ) ( i have seen software run over 10 times as fast on the sparc by removing one function call, that resulted in a often called code path being too deep for the register window. as you don't know how deep the register window will be on your customer's system, and you don't know how far down the call stack you are in the " hot code path ", not using recursion make like more predictable. ) also not risking running out of stack is a benefit.


i agree that a turing machine can do " all the possible mathematical problems ". well, you shouldn't, because it's not true. for example, turing machines cannot determine if polynomials with integer coefficients have integer solutions ( hilbert's tenth problem ). is turing machine “ by definition ” the most powerful machine? no. we can dream up an infinite hierarchy of more powerful machines. however, the turing machine is the most powerful machine that we know, at least in principle, how to build. that's not a definition, though : it is just that we do not have any clue how to build anything more powerful, or if it is even possible. what's the new thing alan turing gave us? a formal definition of algorithm. without such a definition ( e. g., the turing machine ), we have only informal definitions of algorithm, along the lines of " a finitely specified procedure for solving something. " ok, great. but what individual steps are these procedures allowed to take? are basic arithmetic operations steps? is finding the gradient of a curve a step? is finding roots of polynomials a step? is finding integer roots of polynomials a step? each of those seems about as natural. however, if you allow all of them, your " finitely specified procedures " are more powerful than turing machines, which means that they can solve things that can't be solved by algorithms. if you allow all but the last one, you're still within the realms of turing computation. if we didn't have a formal definition of algorithm, we wouldn't even be able to ask these questions. we wouldn't be able to discuss what algorithms can do, because we wouldn't know what an algorithm is.


j. m's comment is right : you can find an interpolating polynomial and differentiate it. there are other ways of deriving such formulas ; typically, they all lead to solving a van der monde system for the coefficients. this approach is problematic when the finite difference stencil includes a large number of points, because the vandermonde matrices become ill - conditioned. a more numerically stable approach was devised by fornberg, and is explained more clearly and generally in a second paper of his. here is a simple matlab script that implements fornberg's method to compute the coefficients of a finite difference approximation for any order derivative with any set of points. for a nice explanation, see chapter 1 of leveque's text on finite difference methods. a bit more on fd formulas : suppose you have a 1d grid. if you use the whole set of grid points to determine a set of fd formulas, the resulting method is equivalent to finding an interpolating polynomial through the whole grid and differentiating that. this approach is referred to as spectral collocation. alternatively, for each grid point you could determine a fd formula using just a few neighboring points. this is what is done in traditional finite difference methods. as mentioned in the comments below, using finite differences of very high order can lead to oscillations ( the runge phenomenon ) if the points are not chosen carefully.


if $ p $ is an infinitely differentiable function such that for each $ x $, there is an $ n $ with $ p ^ { ( n ) } ( x ) = 0 $, then $ p $ is a polynomial. ( note $ n $ depends on $ x $. ) see the discussion in math overflow.


well, a dfa is just a turing machine that's only allowed to move to the right and that must accept or reject as soon as it runs out of input characters. so i'm not sure one can really say that a dfa is natural but a turing machine isn't. critique of the question aside, remember that turing was working before computers existed. as such, he wasn't trying to codify what electronic computers do but, rather, computation in general. my parents have a dictionary from the 1930s that defines computer as " someone who computes " and this is basically where turing was coming from : for him, at that time, computation was about slide rules, log tables, pencils and pieces of paper. in that mind - set, rewriting symbols on a paper tape doesn't seem like a bad abstraction. ok, fine, you're saying ( i hope! ) but we're not in the 1930s any more so why do we still use this? here, i don't think there's any one specific reason. the advantage of turing machines is that they're reasonably simple and we're decently good at proving things about them. although formally specifying a turing machine program to do some particular task is very tedious, once you've done it a few times, you have a reasonable intuition about what they can do and you don't need to write the formal specifications any more. the model is also easily extended to include other natural features, such as random access to the tape. so they're a pretty useful model that we understand well and we also have a pretty good understanding of how they relate to actual computers. one could use other models but one would then have to do a huge amount of translation between results for the new model and the vast body of existing work on what turing machines can do. nobody has come up with a replacement for turing machines that have had big enough advantages to make that look like a good idea.


you can refer to " detecting start of a loop in singly linked list ", here's an excerpt : distance travelled by slowpointer before meeting $ = x + y $ distance travelled by fastpointer before meeting $ = ( x + y + z ) + y = x + 2y + z $ since fastpointer travels with double the speed of slowpointer, and time is constant for both when both pointers reach the meeting point. so by using simple speed, time and distance relation ( slowpointer traveled half the distance ) : \ begin { align * } 2 * \ operatorname { dist } ( \ text { slowpointer } ) & = \ operatorname { dist } ( \ text { fastpointer } ) \ \ 2 ( x + y ) & = x + 2y + z \ \ 2x + 2y & = x + 2y + z \ \ x & = z \ end { align * } hence by moving slowpointer to start of linked list, and making both slowpointer and fastpointer to move one node at a time, they both have same distance to cover. they will reach at the point where the loop starts in the linked list.