id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
4,100 | def issubset( )"""assumes and are lists returns true if each element in is also in and false otherwise ""for in matched false for in if = matched true break if not matchedreturn false return true figure implementation of subset test each time the inner loop is reached it is executed (len( times the function will execut... |
4,101 | simplistic introduction to algorithmic complexity considerfor examplethe code in figure def getbinaryrep(nnumdigits)"""assumes and numdigits are non-negative ints returns numdigits str that is binary representation of ""result 'while result str( % result // if len(resultnumdigitsraise valueerror('not enough digits'for ... |
4,102 | waiting for it to completeunless your computer runs out of memory trying to build list with tens of millions of elements don' even think about trying to run genpowerset on list containing all uppercase and lowercase letters step of the algorithm generates ( len( )binary numbersso the algorithm is exponential in len(ldo... |
4,103 | simplistic introduction to algorithmic complexity on the other handas the plot below and on the right suggeststhere are many situations in which quadratic rate of growth is prohibitive the quadratic curve is rising so quickly that it is hard to see that the log-linear curve is even on the plot the final two plots are a... |
4,104 | structures though we expend fair number of pages in this book talking about efficiencythe goal is not to make you expert in designing efficient programs there are many long books (and even some good long booksdevoted exclusively to that topic in we introduced some of the basic concepts underlying complexity analysis in... |
4,105 | some simple algorithms and data structures this contains few examples intended to give you some intuition about algorithm design many other algorithms appear elsewhere in the book keep in mind that the most efficient algorithm is not always the algorithm of choice program that does everything in the most efficient poss... |
4,106 | contents of an address is constant-time operationthe question becomes whether we can compute the address of the ith element of list in constant time let' start by considering the simple case where each element of the list is an integer this implies that each element of the list is the same sizee four units of memory (f... |
4,107 | some simple algorithms and data structures to the thing initially sought this is what happens each time we use variable to refer to the object to which that variable is bound when we use variable to access list and then reference stored in that list to access another objectwe are going through two levels of indirection... |
4,108 | given the structure of this algorithmit is not surprising that the most straightforward implementation of binary search uses recursionas shown in figure def search(le)"""assumes is listthe elements of which are in ascending order returns true if is in and false otherwise""def bsearch(lelowhigh)#decrements high low if h... |
4,109 | some simple algorithms and data structures if this were book about algorithmswe would now dive into careful analysis using something called recurrence relation but since it isn'twe will take much less formal approach that starts with the question "how do we know that the program terminates?recall that in we asked the s... |
4,110 | sorting algorithms we have just seen that if we happen to know that list is sortedwe can exploit that information to greatly reduce the time needed to search list does this mean that when asked to search list one should first sort it and then perform the searchlet (sortcomplexity( )be the complexity of sorting list sin... |
4,111 | some simple algorithms and data structures we use induction to reason about loop invariants base caseat the start of the first iterationthe prefix is emptyi the suffix is the entire list the invariant is (triviallytrue induction stepat each step of the algorithmwe move one element from the suffix to the prefix we do th... |
4,112 | some simple algorithms and data structures merge sort is prototypical divide-and-conquer algorithm it was invented in by john von neumannand is still widely used like many divide-andconquer algorithms it is most easily described recursively if the list is of length or it is already sorted if the list has more than one ... |
4,113 | some simple algorithms and data structures def merge(leftrightcompare)"""assumes left and right are sorted lists and compare defines an ordering on the elements returns new sorted (by comparelist containing the same elements as (left rightwould contain ""result [ , while len(leftand len(right)if compare(left[ ]right[ ]... |
4,114 | involves making copies of the list this means that its space complexity is (len( )this can be an issue for large lists exploiting functions as parameters suppose we want to sort list of names written as firstname lastnamee the list ['chris terman''tom brady''eric grimson''gisele bundchen'figure defines two ordering fun... |
4,115 | some simple algorithms and data structures sorting in python the sorting algorithm used in most python implementations is called timsort the key idea is to take advantage of the fact that in lot of data sets the data is already partially sorted timsort' worst-case performance is the same as merge sort'sbut on average i... |
4,116 | both the list sort method and the sorted function provide stable sorts this means that if two elements are equal with respect to the comparison used in the sorttheir relative ordering in the original list (or other iterable objectis preserved in the final list hash tables if we put merge sort together with binary searc... |
4,117 | some simple algorithms and data structures designing good hash functions is surprisingly challenging the problem is that one wants the outputs to be uniformly distributed given the expected distribution of inputs supposefor examplethat one hashed surnames by performing some calculation on the first three letters in the... |
4,118 | class intdict(object)""" dictionary with integer keys""def __init__(selfnumbuckets)"""create an empty dictionary""self buckets [self numbuckets numbuckets for in range(numbuckets)self buckets append([]def addentry(selfdictkeydictval)"""assumes dictkey an int adds an entry ""hashbucket self buckets[dictkey%self numbucke... |
4,119 | some simple algorithms and data structures when we ran this code it printed the value of the intdict is{ : , : , : , : , : , : , : , : : , : , : , : , : , : , : , : : , : , : , : the buckets are[( )[( )[[[[[( )[( )[( )[[( )[[( )[[[[[( )[( )[( )( )[( )( )[[( )( )[[( )( )( )[( )[[[( )when we violate the abstraction barri... |
4,120 | often text is the best way to communicate informationbut sometimes there is lot of truth to the chinese proverb(" picture' meaning can express ten thousand words"yet most programs rely on textual output to communicate with their users whybecause in many programming languages presenting visual data is too hard fortunate... |
4,121 | plotting and more about classes the bar at the top contains the name of the windowin this case "figure the middle section of the window contains the plot generated by the invocation of pylab plot the two parameters of pylab plot must be sequences of the same length the first specifies the -coordinates of the points to ... |
4,122 | plotting and more about classes the code pylab figure( #create figure pylab plot([ , , , ][ , , , ]#draw on figure pylab figure( #create figure pylab plot([ , , , ][ , , , ]#draw on figure pylab savefig('figure-addie'#save figure pylab figure( #go back to working on figure pylab plot([ , , , ]#draw again on figure pyla... |
4,123 | plotting and more about classes if we look at the codewe can deduce that this is plot showing the growth of an initial investment of $ , at an annually compounded interest rate of howeverthis cannot be easily inferred by looking only at the plot itself that' bad thing all plots should have informative titlesand all axe... |
4,124 | it' also possible to change the type size and line width used in plots this can be done using keyword arguments in individual calls to functionse the code principal #initial investment interestrate years values [for in range(years )values append(principalprincipal +principal*interestrate pylab plot(valueslinewidth pyla... |
4,125 | plotting and more about classes the default values used in most of the examples in this book were set with the code #set line width pylab rcparams['lines linewidth' #set font size for titles pylab rcparams['axes titlesize' #set font size for labels on axes pylab rcparams['axes labelsize' #set size of numbers on -axis p... |
4,126 | class mortgage(object)"""abstract class for building different kinds of mortgages""def __init__(selfloanannratemonths)"""create new mortgage""self loan loan self rate annrate/ self months months self paid [ self owed [loanself payment findpayment(loanself ratemonthsself legend none #description of mortgage def makepaym... |
4,127 | plotting and more about classes typearraywhich pylab inherits from numpy the invocation pylab array makes this explicit there are number of convenient ways to manipulate arrays that are not readily available for lists in particularexpressions can be formed using arrays and arithmetic operators considerfor examplethe co... |
4,128 | class fixed(mortgage)def __init__(selfloanrmonths)mortgage __init__(selfloanrmonthsself legend 'fixedstr( * '%class fixedwithpts(mortgage)def __init__(selfloanrmonthspts)mortgage __init__(selfloanrmonthsself pts pts self paid [loan*(pts/ )self legend 'fixedstr( * '%'str(ptspointsclass tworate(mortgage)def __init__(self... |
4,129 | plotting and more about classes def plotmortgages(mortsamt)styles [' -'' '' :'#give names to figure numbers payments cost balance netcost pylab figure(paymentspylab title('monthly payments of different $str(amtmortgages'pylab xlabel('months'pylab ylabel('monthly payments'pylab figure(costpylab title('cash outlay of dif... |
4,130 | produces plots that shed some light on the mortgages discussed in the first plotwhich was produced by invocations of plotpaymentssimply plots each payment of each mortgage against time the box containing the key appears where it does because of the value supplied to the keyword argument loc used in the call to pylab le... |
4,131 | statistics there is something very comforting about newtonian mechanics you push down on one end of leverand the other end goes up you throw ball up in the airit travels parabolic pathand comes down !in shorteverything happens for reason the physical world is completely predictable place--all future states of physical ... |
4,132 | which we live can be accurately modeled only as stochastic processes process is stochastic if its next state depends upon both previous states and some random element stochastic programs program is deterministic if whenever it is run on the same inputit produces the same output notice that this is not the same as sayin... |
4,133 | stochastic programsprobabilityand statistics import random def rolldie()"""returns random int between and ""return random choice([ , , , , , ]def rolln( )result 'for in range( )result result str(rolldie()print result figure roll die nowimagine running rolln( would you be more surprised to see it print or orto put it an... |
4,134 | this can be computed as followsthe probability of not rolling on any single roll is / the probability of not rolling on either the first or the second roll is ( / )*( / )or ( / ) sothe probability of not rolling ten times in row is ( / ) slightly more than we will return to the subject of probability in bit more detail... |
4,135 | stochastic programsprobabilityand statistics def flip(numflips)heads for in range(numflips)if random random( heads + return heads/numflips def flipsim(numflipspertrialnumtrials)fracheads [for in range(numtrials)fracheads append(flip(numflipspertrial)mean sum(fracheads)/len(fracheadsreturn mean figure flipping coin try ... |
4,136 | experiments approaches the expected value as the number of experiments goes to infinity it is worth noting that the law of large numbers does not implyas too many seem to thinkthat if deviations from expected behavior occurthese deviations are likely to be evened out by opposite deviations in the future this misapplica... |
4,137 | stochastic programsprobabilityand statistics def flipplot(minexpmaxexp)"""assumes minexp and maxexp positive integersminexp maxexp plots results of **minexp to **maxexp coin flips""ratios [diffs [xaxis [for exp in range(minexpmaxexp )xaxis append( **expfor numflips in xaxisnumheads for in range(numflips)if random rando... |
4,138 | it' hard to see much of anything in the plot on the rightwhich is mostly flat line this too is deceptive even though there are sixteen data pointsmost of them are crowded into small amount of real estate on the left side of the plotso that the detail is impossible to see this occurs because values on the -axis range fr... |
4,139 | stochastic programsprobabilityand statistics of the population (and since we are usually dealing with infinite populationse all possible sequences of coin flipsthis is usually impossibleof coursethis is not to say that an estimate cannot be precisely correct we might flip coin twiceget one heads and one tailsand conclu... |
4,140 | the implementation of flipplot uses two helper functions the function makeplot contains the code used to produce the plots the function runtrial simulates one trial of numflips coins def makeplot(xvalsyvalstitlexlabelylabelstylelogx falselogy false)"""plots xvals vs yvals with supplied titles and labels ""pylab figure(... |
4,141 | stochastic programsprobabilityand statistics let' try flipplot ( it generates the plots this is encouraging the ratio heads/tails is converging towards and the log of the standard deviation is falling linearly with the log of the number of flips per trial by the time we get to about coin flips per trialthe standard dev... |
4,142 | this produces the additional plots as expectedthe absolute difference between the numbers of heads and tails grows with the number of flips furthermoresince we are averaging the results over twenty trialsthe plot is considerably smoother than when we plotted the results of single trial but what' up with the last plotth... |
4,143 | stochastic programsprobabilityand statistics figure contains version of flipplot that plots coefficients of variation def flipplot (minexpmaxexpnumtrials)"""assumes minexp and maxexp positive intsminexp maxexp numtrials positive integer plots summaries of results of numtrials trials of **minexp to **maxexp coin flips""... |
4,144 | stochastic programsprobabilityand statistics it produces the additional plots in this case we see that the plot of coefficient of variation for the heads/tails ratio is not much different from the plot of the standard deviation this is not surprisingsince the only difference between the two is the division by the meana... |
4,145 | stochastic programsprobabilityand statistics distributions histogram is plot designed to show the distribution of values in set of data the values are first sortedand then divided into fixed number of equalwidth bins plot is then drawn that shows the number of elements in each bin considerfor examplethe code vals [ #gu... |
4,146 | def flip(numflips)heads for in range(numflips)if random random( heads + return heads/numflips def flipsim(numflipspertrialnumtrials)fracheads [for in range(numtrials)fracheads append(flip(numflipspertrial)mean sum(fracheads)/len(fracheadssd stddev(fracheadsreturn (fracheadsmeansddef labelplot(numflipsnumtrialsmeansd)py... |
4,147 | stochastic programsprobabilityand statistics notice that while the means in both plots are about the samethe standard deviations are quite different the spread of outcomes is much tighter when we flip the coin times per trial than when we flip the coin times per trial to make this clearwe have used pylab xlim to force ... |
4,148 | estimate almost alwaysincreasing the confidence level will widen the confidence interval the calculation of confidence interval generally requires assumptions about the nature of the space being sampled it assumes that the distribution of errors of estimation is normal and has mean of zero the empirical rule for normal... |
4,149 | stochastic programsprobabilityand statistics def showerrorbars(minexpmaxexpnumtrials)"""assumes minexp and maxexp positive intsminexp maxexp numtrials positive integer plots mean fraction of heads with error bars""meanssds [][xvals [for exp in range(minexpmaxexp )xvals append( **expfracheadsmeansd flipsim( **expnumtria... |
4,150 | exponential and geometric distributions exponential distributionsunlike uniform distributionsoccur quite commonly they are often used to model inter-arrival timese of cars entering highway or requests for web page they are especially important because they have the memoryless property considerfor examplethe concentrati... |
4,151 | stochastic programsprobabilityand statistics this is an example of exponential decay in practiceexponential decay is often talked about in terms of half-lifei the expected time required for the initial value to decay by one can also talk about the half-life of single item for examplethe half-life of single radioactive ... |
4,152 | def successfulstarts(eventprobnumtrials)"""assumes eventprob is float representing probability of single attempt being successful numtrials positive int returns list of the number of attempts needed before success for each trial ""triesbeforesuccess [for in range(numtrials)consecfailures while random random(eventprobco... |
4,153 | stochastic programsprobabilityand statistics how often does the better team winthus far we have looked at using statistical methods to help understand possible outcomes of games in which skill is not intended to play role it is also common to apply these methods to situations in which there ispresumablysome skill invol... |
4,154 | def playseries(numgamesteamprob)"""assumes numgames an odd integerteamprob float between and returns true if better team wins series""numwon for game in range(numgames)if random random(<teamprobnumwon + return (numwon numgames// def simseries(numseries)prob fracwon [probs [while prob < serieswon for in range(numseries)... |
4,155 | stochastic programsprobabilityand statistics world series be in order for us to get results that would allow us to reject the null hypothesisi the hypothesis that the teams are evenly matchedthe code in figure simulates instances of series of varying lengthsand plots an approximation of the probability of the better te... |
4,156 | stochastic programsprobabilityand statistics hashing and collisions in section we pointed out that by using larger hash table one could reduce the incidence of collisionsand thus reduce the expected time to retrieve value we now have the intellectual tools needed to examine that tradeoff more precisely firstlet' get pr... |
4,157 | stochastic programsprobabilityand statistics def collisionprob(nk)prob for in range( )prob prob (( )/float( )return prob if we try collisionprob( we get probability of about of there being at least one collision if we consider insertionsthe probability of collision is nearly one does that seem bit high to youlet' write... |
4,158 | visualization in the scottish botanist robert brown observed that pollen particles suspended in water seemed to float around at random he had no plausible explanation for what came to be known as brownian motionand made no attempt to model it mathematically clear mathematical model of the phenomenon was first presented... |
4,159 | random walks and more about data vizualization secondsif she takes many stepsis she likely to move ever further from the originor is she more likely to wander back to the origin over and overand end up not far from where she startedlet' write simulation to find out before starting to design programit is always good ide... |
4,160 | to the kinds of things that appear in the situation we are attempting to model three obvious types are locationfieldand drunk as we look at the classes providing these typesit is worthwhile to think about what each might imply about the kinds of simulation models they will allow us to build let' start with location cla... |
4,161 | random walks and more about data vizualization class field(object)def __init__(self)self drunks {def adddrunk(selfdrunkloc)if drunk in self drunksraise valueerror('duplicate drunk'elseself drunks[drunkloc def movedrunk(selfdrunk)if drunk not in self drunksraise valueerror('drunk not in field'xdistydist drunk takestep(c... |
4,162 | the parameter dclass of simwalks is of type classand is used in the first line of code to create drunk of the appropriate subclass laterwhen drunk takestep is invoked from field movedrunkthe method from the appropriate subclass is automatically selected the function drunktest also has parameterdclassof type class it is... |
4,163 | random walks and more about data vizualization when we executed drunktest(( ) usualdrunk)it printed usualdrunk random walk of steps mean cv max min usualdrunk random walk of steps mean cv max min usualdrunk random walk of steps mean cv max min usualdrunk random walk of steps mean cv max min this is surprisinggiven the ... |
4,164 | random walks and more about data vizualization when the corrected version of the simulation is run on our two simple casesit yields exactly the expected answersusualdrunk random walk of steps mean cv nan max min usualdrunk random walk of steps mean cv max min when run on longer walks it printed usualdrunk random walk o... |
4,165 | random walks and more about data vizualization biased random walks now that we have working simulationwe can start modifying it to investigate other kinds of random walks supposefor examplethat we want to consider the behavior of drunken farmer in the northern hemisphere who hates the coldand even in his drunken stupor... |
4,166 | this is quite bit of output to digest it does appear that our heat-seeking drunk moves away from the origin faster than the other two kinds of drunk howeverit is not easy to digest all of the information in this output it is once again time to move away from textual output and start using plots since we are showing num... |
4,167 | random walks and more about data vizualization def simdrunk(numtrialsdclasswalklengths)meandistances [cvdistances [for numsteps in walklengthsprint 'starting simulation of'numsteps'stepstrials simwalks(numstepsnumtrialsdclassmean sum(trials)/float(len(trials)meandistances append(meancvdistances append(stddev(trials)/me... |
4,168 | def getfinallocs(numstepsnumtrialsdclass)locs [ dclass(origin location( for in range(numtrials) field( adddrunk(doriginfor in range(numsteps) movedrunk(dlocs append( getloc( )return locs def plotlocs(drunkkindsnumstepsnumtrials)stylechoice styleiterator((' +'' ^''mo')for dclass in drunkkindslocs getfinallocs(numstepsnu... |
4,169 | random walks and more about data vizualization but why do there appear to be far fewer circle markers than triangle or markersbecause many of the ewdrunk' walks ended up at the same place this is not surprisinggiven the small number of possible endpoints ( for the ewdrunk also the circle markers seem to be fairly unifo... |
4,170 | none of these simulations is interesting in its own right (in the next we will look at more intrinsically interesting simulations but there are some points worth taking awayinitially we divided our simulation code into four separate chunks three of them were classes (locationfieldand drunkcorresponding to abstract data... |
4,171 | random walks and more about data vizualization class oddfield(field)def __init__(selfnumholesxrangeyrange)field __init__(selfself wormholes {for in range(numholes) random randint(-xrangexrangey random randint(-yrangeyrangenewx random randint(-xrangexrangenewy random randint(-yrangeyrangenewloc location(newxnewyself wor... |
4,172 | in the previous two we looked at different ways of using randomness in computations many of the examples we presented fall into the class of computation known as monte carlo simulation stanislaw ulam and nicholas metropolis coined the term monte carlo simulation in in homage to the games of chance played in the casino ... |
4,173 | monte carlo simulation pascal' problem most of the early work on probability theory revolved around games using dice reputedlypascal' interest in the field that came to be known as probability theory began when friend asked him whether or not it would be profitable to bet that within twenty-four rolls of pair of dice h... |
4,174 | when run the first timethe call checkpascal( printed probability of winning this is indeed quite close to ( / ) typing )** into the python shell produces pass or don' passnot all questions about games of chance are so easily answered in the game crapsthe shooter (the person who rolls the dicechooses between making "pas... |
4,175 | monte carlo simulation class crapsgame(object)def __init__(self)self passwinsself passlosses ( , self dpwinsself dplossesself dppushes ( , , def playhand(self)throw rolldie(rolldie(if throw = or throw = self passwins + self dplosses + elif throw = or throw = or throw = self passlosses + if throw = self dppushes + elses... |
4,176 | monte carlo simulation for exampleif you made pass line bets and won half of themyour roi would be = if you bet the don' pass line times and had wins and pushes the roi would be - - note that in crapssim we use xrange rather than range in the for loops in anticipation of running large simulations recall that in python ... |
4,177 | monte carlo simulation it looks as if it would be good idea to avoid the pass line--where the expected return on investment is loss but the don' pass line looks like pretty good bet or does itlooking at the standard deviationsit seems that perhaps the don' pass line is not such good bet after all recall that under the ... |
4,178 | using table lookup to improve performance you might not want to try running crapssim( at home it takes long time to complete on most computers that raises the question of whether there is simple way to speed up the simulation the complexity of crapssim is (playhand)*handspergame*numgames the running time of playhand de... |
4,179 | monte carlo simulation def playhand(self)#an alternativefasterimplementation of playhand pointsdict { : : : : : :throw rolldie(rolldie(if throw = or throw = self passwins + self dplosses + elif throw = or throw = or throw = self passlosses + if throw = self dppushes + elseself dpwins + elseif random random(<pointsdict[... |
4,180 | monte carlo simulation measured from the outside of the wall and the diameter from the insideor perhaps it' just poetic license we leave it to the reader to decide archimedes of syracuse ( - bcderived upper and lower bounds on the value of by using high-degree polygon to approximate circular shape using polygon with si... |
4,181 | monte carlo simulation if you try buffon' experimentyou'll soon realize that the places where the needles land are not truly random moreovereven if you could drop them randomlyit would take very large number of needles to get an approximation of as good as even the bible' fortunatelycomputers can randomly drop simulate... |
4,182 | monte carlo simulation def throwneedles(numneedles)incircle for needles in xrange( numneedles ) random random( random random(if ( * * )** < incircle + #counting needles in one quadrant onlyso multiply by return *(incircle/float(numneedles)def getest(numneedlesnumtrials)estimates [for in range(numtrials)piguess thrownee... |
4,183 | monte carlo simulation notion it is not sufficient to produce good answer we have to have valid reason to be confident that it is in fact good answer and when we drop large enough number of needlesthe small standard deviation gives us reason to be confident that we have correct answer rightnot exactly having small stan... |
4,184 | as the th century progressedthe limitations of this approach became increasingly clear reasons for this includean increased interest in the social sciencese economicsled to desire to construct good models of systems that were not mathematically tractable as the systems to be modeled grew increasingly complexit seemed e... |
4,185 | monte carlo simulation in static modeltime plays no essential role the needle-dropping simulation used to estimate in this is an example of static simulation in dynamic modeltimeor some analogplays an essential role in the series of random walks simulated in the number of steps taken was used as surrogate for time in d... |
4,186 | this is all about understanding experimental data we will make extensive use of plotting to visualize the dataand will return to the topic of what is and what is not valid statistical conclusion we will also talk about the interplay between physical and computational experiments the behavior of springs springs are wond... |
4,187 | understanding experimental data generations of physics students have learned to estimate spring constants using an experimental apparatus similar to that pictured here the basic idea is to estimate the force stored in the spring by measuring the displacement caused by exerting known force on the spring we start with sp... |
4,188 | we ran such an experimentand typed the results into file named springdata txtdistance (mmass (kg the function in figure reads data from file such as the one we savedand returns lists containing the distances and masses def getdata(filename)datafile open(filename' 'distances [masses [discardheader datafile readline(for ... |
4,189 | understanding experimental data when plotdata('springdata txt'is runit produces the plot on the left this is not what hooke' law predicts hooke' law tells us that the distance should increase linearly with the massi the points should lie on straight line the slope of which is determined by the spring constant of course... |
4,190 | the call pylab polyfit(observedxvalsobservedyvalsnfinds the coefficients of polynomial of degree that provides best leastsquares fit for the set of points defined by the arrays observedxvals and observedyvals for examplethe call pylab polyfit(observedxvalsobservedyvals will find line described by the polynomial ax bwhe... |
4,191 | understanding experimental data def fitdata(inputfile)massesdistances getdata(inputfiledistances pylab array(distancesmasses pylab array(massesforces masses* pylab plot(forcesdistances'bo'label 'measured displacements'pylab title('measured displacement of spring'pylab xlabel('|force(newtons)'pylab ylabel('distance (met... |
4,192 | go on to assume that the fitted curve is the description of the real situationand the raw data merely an indication of experimental error this can be dangerous recall that we started with theory that there should be linear relationship between the and valuesnot cubic one let' see what happens if we use our cubic fit to... |
4,193 | understanding experimental data determine which line is better fit for the databut that would be beside the point this is not question that can be answered by statistics after all we could throw out all the data except any two points and know that polyfit would find line that would be perfect fit for those two points o... |
4,194 | def gettrajectorydata(filename)datafile open(filename' 'distances [heights heights heights heights [],[],[],[discardheader datafile readline(for line in datafiledh line split(distances append(float( )heights append(float( )heights append(float( )heights append(float( )heights append(float( )datafile close(return (dista... |
4,195 | understanding experimental data coefficient of determination when we fit curve to set of datawe are finding function that relates an independent variable (inches horizontally from the launch point in this exampleto predicted value of dependent variable (inches above the launch point in this exampleasking about the good... |
4,196 | when the lines of code print 'rsquare of linear fit ='rsquared(meanheightsaltitudesand print 'rsquare of quadratic fit ='rsquared(meanheightsaltitudesare inserted after the appropriate calls to pylab plot in processtrajectoriesthey print rsquared of linear fit rsquared of quadratic fit roughly speakingthis tells us tha... |
4,197 | understanding experimental data def gethorizontalspeed(abcminxmaxx)"""assumes minx and maxx are distances in inches returns horizontal speed in feet per second""inchesperfoot xmid (maxx minx)/ ypeak *xmid** *xmid *inchesperfoot #accel of gravity in inches/sec/sec ( *ypeak/ )** print 'horizontal speed ='int(xmid/( *inch... |
4,198 | the code in figure produces the plot the fit is clearly good onefor these data points howeverlet' look at what the model predicts for when we add the code pred to *( ** *( ** *( ** ) * print 'model predicts that ** is roughly'round(pred to print 'actual value of ** is' ** to the end of figure it printsmodel predicts th... |
4,199 | understanding experimental data model for an exponentially distributed set of data pointsas illustrated by the code in figure we use polyfit to find curve that fits the values and log of the values notice that we use yet another python standard library modulemathwhich supplies log function import math #define an arbitr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.