当前位置:文档之家› Random networks created by biological evolution

Random networks created by biological evolution

Random networks created by biological evolution
Random networks created by biological evolution

a r X i v :c o n d -m a t /0004407v 2 [c o n d -m a t .s t a t -m e c h ] 9 A u g 2000

Random networks created by biological evolution

Frantiˇs ek Slanina ?and Miroslav Kotrla ??

Institute of Physics,Academy of Sciences of the Czech Republic,Na Slovance 2,CZ-18221Praha 8,Czech Republic

We investigate a model of evolving random network,introduced by us previously [Phys.Rev.Lett.83,5587(1999)].The model is a generalization of the Bak-Sneppen model of biological evolution,with the modi?cation that the underlying network can evolve by adding and removing sites.The behavior and the averaged properties of the network depend on the parameter p ,the probability to establish link to the newly introduced site.For p =1the system is self-organized critical,with two distinct power-law regimes with forward-avalanche exponents τ=1.98±0.04and τ′=1.65±0.05.The average size of the network diverge as power-law when p →1.We study various geometrical properties of the network:probability distribution of sizes and connectivities,size and number of disconnected clusters and the dependence of mean distance between two sites on the cluster size.The connection with models of growing networks with preferential attachment is discussed.PACS numbers:05.40.-a,87.10.+e,87.23.Kg

I.INTRODUCTION

Irregular networks or random graphs [1]composed of units of various kind are very frequent both in nature and society (which is,however,nothing but a special segment of nature).Examples range from vulcanized polymers,silica glasses,force chains in granular materials [2],mesoscopic quantum wires [3]to food webs [4],herd-ing e?ects in economics [5],world-wide-web links [6,7],“small-world”networks of personal contacts between hu-mans [8,9]and scienti?c collaboration networks [10].Modeling of such networks is not quite easy and ana-lytical results are relatively rare (examples,without any pretence of completeness,can be found in [1,5,11,12]).Numerical simulations are still one of the principal tools.However,even in the case when the properties of a given class of random networks are relatively well established,either analytically or numerically,as is the case of small-world networks,the serious question remains,why do these networks occur in nature.In other words,what are the dynamical processes,which generate these networks.Indeed,one can study,for example,various networks of mutual dependence of species in a model of co-evolution [13–15],but it is di?cult to infer from these studies only,which networks are closer to the reality that the others.In the context of biological evolution models,there was recently a few attempts to let the networks evolve freely,in order to check,which types of topologies might corre-spond to “attractors”of the process of natural evolution [16–21].

The model introduced by us in a preceding Letter [18]is based on extremal dynamics and basically follows the Bak-Sneppen model of biological evolution [14].Ex-tremal dynamics (ED)models [22]are used in wide area of problems,ranging from growth in disordered medium [23],dislocation movement [24],friction [25]to biologi-cal evolution [14].Among them,the Bak-Sneppen (BS)model plays the role of a testing ground for various ana-lytical as well as numerical approaches (see for example

[22,26–31]).

The idea of ED is the following.The dynamical system in question is composed of a large number of simple units,connected in a network.Each site of the network hosts one unit.The state of each unit is described by a sin-gle dynamical variable b ,called barrier.In each step,the unit with minimum b is mutated by updating the barrier.The e?ect of the mutation on the environment is taken into account by changing b also at all sites connected to the minimum site by a network link.Because a perturba-tion can propagate through the links,we should expect that the topology of the network can a?ect substantially the ED evolution.

General feature of ED models is the avalanche dynam-ics.The forward λ-avalanches are de?ned as follows [22].For ?xed λwe de?ne active sites as those having bar-rier b <λ.Appearance of one active site can lead to avalanche-like proliferation of active sites in successive time steps.The avalanche stops,when all active sites dis-appear again.Generically,there is a value of λ,for which the probability distribution of avalanche sizes obeys a power law without any parameter tuning,so that the ED models are classi?ed as a subgroup of self-organized critical models [32].(This,of course,can hold only for networks of unlimited size.)The set of exponents de-scribing the critical behavior determines the dynamical universality class the model belongs to.

It was found that the universality class depends on the topology of the https://www.doczj.com/doc/0e13999128.html,ually,regular hyper-cubic networks [22]or Cayley trees [31]are investigated.For random neighbor networks,mean-?eld solution was found to be exact [33,27].Also the tree models [31]were found to belong to the mean-?eld universality class.A one-dimensional model in which the links were wired ran-domly with probability decaying as a power μof the dis-tance was introduced [34,35].It was found that the values of critical exponents depend continuously on μ.The BS model on a small-world network was also studied [36].Recently,BS model on random networks,produced by

bond percolation on fully connected lattice,was studied [16].Two universality classes were found.Above the percolation threshold,the system belongs to the mean-?eld universality class,while exactly at the percolation threshold,the avalanche exponent is di?erent.A dynam-ics changing the topology in order to drive the network to critical connectivity was suggested.

There are also several recent results for random net-works produced by di?erent kind of dynamics than ED, especially for the threshold networks[19]and Boolean networks[20,21].

The geometry of the world-wide web was intensively studied very recently.It was found experimentally that the network exhibits scale-free characteristics,measured by the power-law distribution of connectivities of the sites [6,37].Similar power-law behavior was observed also in the actor collaboration graph and in the power grids[6].

A model was suggested[6]to explain this behavior,whose two main ingredients are continual growth and prefer-ential attachment of new links,where sites with higher connectivity having higher probability to receive addi-tional links.The latter feature resembles the behavior of additive-multiplicative random processes,which are well known to produce power-law distributions[38,39].

The model introduced in[6]is exactly soluble[40]. Variants including aging of sites[41,42],decaying and rewiring links[43,44]were also studied.The preferen-tial attachment rule,which apparently requires unreal-istic knowledge of connectivities of the whole network before a single new link is established,was justi?ed in a very recent work[45],where higher probability of attach-ment at highly connected sites results from local search by walking on the network.

In the preceding Letter[18]we concentrated on the self-organized critical behavior and extinction dynamics of a model in which the network changes dynamically by adding and removing sites.It was shown that the extinc-tion exponent is larger than the upper bound for the BS model(given by the mean-?eld value)and is closer to the experimentally found value than any previous version of the BS model.In the present work we introduce in Sec. II a generalized version of the model de?ned in[18]and further investigate the self-organized critical behavior in Sec.III.However,our main concern will be about the geometric properties of the network,produced during the dynamics.These results are presented in Sec.IV.Sec-tion V makes conclusions from the results obtained.

II.EVOLUTION MODEL ON EVOL VING

NETWORK

We consider a system composed of varying number n u of units connected in a network,subject to extremal dy-namics.Each unit bears a dynamical variable b.In the context of biological evolution these units are species and b represent the barrier against mutations.For the main novelty of our model consists in adding(speciation)and removing(extiction)units,let us?rst de?ne the rules for extinction and speciation.The rules determining which of the existing units will undergo speciation or extinction will be speci?ed afterwards.

(i)If a unit is chosen for extinction,it is completely removed from the network without any substitution and all links it has,are broken.

(ii)If a unit is chosen for speciation,it acts as a “mother”giving birth to a new,“daughter”unit.A new unit is added into the system and the links are established between the new unit and the neighbors of the“mother”unit:each link of the“mother”unit is inherited with the probability p by the“daughter”unit.This rule re?ects the fact that the new unit is to a certain extent a copy of the original,so the relations to the environment will be initially similar to the ones the old unit has.Moreover, if a unit which speciates has only one neighbor,a link between“mother”and“daughter”is also established. The extremal dynamics rule for our model is the fol-lowing.

(iii)In each step,the unit with minimum b is found and mutated.The barrier of the mutated unit is replaced by a new random value b′taken from uniform distribu-tion on the interval(0,1).Also the barriers of all its neighbors are replaced by new random numbers from the same distribution.

The rules determining whether a unit is chosen for ex-tiction or speciation are the following.

(iv)If the newly assigned barrier of the mutated unit b′is larger than new barriers of all its neighbors,the unit is chosen for speciation.If b′is lower than barriers of all neighbors,the unit is chosen for extinction.In other cases neither extinction nor speciation occcurs.As a boundary condition,we use the following exception:if the network consists of a single isolated unit only,it is always chosen for speciation.

(v)If a unit is chosen for extinction,all its neighbors which are not connected to any other unit also chosen for extinction.We call this kind of extinctions singular extinctions.

The rule(iv)is motivated by the following consider-ations.We assume,that well-adapted units proliferate more rapidly and chance for speciation is bigger.How-ever,if the local biodiversity,measured by connectivity of the unit,is bigger,there are fewer empty ecological niches and the probability of speciation is lower.On the other hand,poorly adapted units are more vulnerable to extinction,but at the same time larger biodiversity (larger connectivity)may favor the survival.Our rule corresponds well to these assumptions:speciation occurs preferably at units with high barrier and surrounded by fewer neighbors,extinction is more frequent at units with lower barriers and lower connectivity.Moreover,we sup-pose that a unit completely isolated from the rest of the ecosystem has very low chance to survive.This leads to the rule(v).

From the rule(iv)alone follows equal probability of

adding and removing a unit,because the new random barriers b are taken from uniform distribution.At the same time the rule (v)enhances the probability of the removal.Thus,the probability of speciation is slightly lower than the probability of extinction.

(a)

(b)

after

(c)

after

FIG.1.Schematic illustration of the dynamical rules of the model.Speciation is shown in (a),where full square repre-sents the extremal unit,which speciates,full circle the new,daughter unit,and open circles other units,not a?ected by the speciation event.The dotted link intends to illustrate that for p <1some of the mother’s links may not be inherited by the daughter.Extinction is shown in (b),where the extremal unit,which is removed,is indicated by full square.The unit denoted by full circle is the neighbor removed by the singular extinction.In (c)an example of an extinction event is shown,which leads to the splitting of the network into disconnected clusters.

The degree of disequilibrium between the two depends on the topology of the network at the moment and can be quanti?ed by the frequency of singular extinctions.The number of units n u perform a biased random walk with

re?ecting boundary at n u =1.The bias towards small values is not constant,though,but ?uctuates as well.The above rules are illustrated by the examples shown in Fig. 1.The networks in (a)show the e?ect of the speciation:a new site is created and some to the links to the mother’s neighbors are established.In (b)the extinction is shown.One of the units is removed also due to a singular extinction (rule (v)).In (c)we illustrate the possibility that in the extinction event the network can be split into several disconnected clusters.

III.SELF-ORGANIZED CRITICAL BEHA VIOR

A.Crossover scaling

The model investigated in the preceding Letter [18]corresponds to the value p = 1.We found that in this case the model is self-organized critical.We de-?ned newly the mass extinctions,as number of units re-moved during an avalanche.The distribution of mass extinctions obeys a power law with the exponent τext =2.32±0.05.In this section we present improved analysis of the data for the self-organized critical behavior.

FIG.2.Rescaled distribution of forward avalanches in the case p =1,for the values λ=0.03(△),λ=0.05(?),λ=0.1(+),λ=0.2(3),λ=0.4(×),λ=0.6(2),The superscript

>in P >

fwd (s )is to indicate that we count all avalanches larger than s .In the inset we plot the dependence of the scaling parameters s cross (+)and f cross (×)on λ.The full line is

the power-law λ?σ′

with the exponent σ′=3.5.The number of time steps was 3·108and the data are averaged over 12independent runs.

We measured the distribution of forward λ-avalanches [22]and we observed,contrary to the BS model that two power-law regimes with two di?erent exponents oc-cur.The crossover value s cross which separates the two

regimes depends onλ.We observed that the distribu-tions for di?erentλcollapse onto single curve,if plotted against the rescaled avalanche size s/s cross,i.e.

P>fwd(s)·f cross=g(s/s cross)(1)

where g(x)~x?τ+1for x?1and

g(x)~x?τ′+1for

x?1.The data are plotted in Fig. 2.For the values of the exponents,we foundτ=1.98±0.04andτ′= 1.65±0.05.

We investigated the dependence of the scaling parame-ters s cross and f cross onλand we found that both of them behave as a power law with approximately equal expo-nent,s cross~f cross~λ?σ′withσ′?3.5(see inset in the Fig.2).The role of criticalλat which the distribution of forward avalanches follows a power law is assumed by the valueλ=0.This result is easy to understand.In fact,in models with?xed(or at least bounded)connec-tivity c,the criticalλis roughly1/c.As will be shown in the next section,in our case the size of the system and average connectivity grows without limits,and thus the criticalλtends to zero.Note that it is di?cult to see this result without resort to the data collapse(1).Indeed,for any?nite time of the simulation,the connectivity and the system size reaches only a limited value and the crit-icalλseen in the distribution of forward avalanches has apparently non-zero value.

https://www.doczj.com/doc/0e13999128.html,parison with the Bak-Sneppen model

If we compare the above?ndings with the BS model, we can deduce that in our model,with p=1,the expo-nentτcorresponds to the usual forward-avalanche expo-nent,while the exponentτ′is new.The above described scaling(1)breaks down for p<1because the connectiv-ity and the system size are limited(cf.next section). The main di?erence from the usual BS model is the existence of the second power-law regime,for s?s cross. It can be particularly well observed for values ofλclose to 1,where the crossover avalanche size s cross is small.We have seen that such avalanches start and end mostly when number of units is close to its minimum value equal to1. Between these events the evolution of the number of units is essentially a random walk,because singular extinctions are rare[18].This fact can explain,why the exponentτ′is not too far from the value3/2corresponding to the distribution of?rst returns to the origin for the random walk.The di?erence is probably due to the presence of singular extinctions.

We measured also the distribution of barriers P(b) and the distribution of barriers on the extremal site P min(b min).In Fig.3we can compare the results for p=1and p=0.95.The sharp step observed in BS model is absent here,because the connectivity is not uni-form.(For comparison,we measured also the barrier dis-tribution in the model of Ref.[16],where the network is static,but the connectivity is not uniform.Also in that case the step was absent and the distribution was qual-itatively very similar to the one shown in Fig. 3.)The large noise level for b close to1is due to the fact that units with larger b undergo mutations rarely.

FIG.3.Distribution of barriers b(full line)and minimum barriers b min(dashed line)for p=0.95(upper plot)and p=1 (lower plot).In both cases the number of time steps was107.

https://www.doczj.com/doc/0e13999128.html,WORK GEOMETRY

In this section we analyze the geometrical properties of the network and their dependence on the parameter p.

A.Size of the network

The?rst important feature of the networks created by the dynamics of the model is their size,or the number of units within the network.This is a strongly?uctuating quantity,but on average it grows initially and after some time it saturates and keeps?uctuating around some aver-age value,which depend on p.Fig.4shows the probabil-ity distribution of number of units n u for several values of p.The average number of units n u was computed from these distributions and its dependence on p is shown in the inset of Fig.4.We can see that the average network size diverges for p→1as a power law, n u ∝(1?p)?αn with the exponentαn?0.8.

We can see from Fig.5that the distribution of number of units has an exponential tail.This corresponds to the fact that the time evolution of the network size is a

random walk with re?ecting boundary at n u =1,with a bias to lower values,caused by the singular extinctions (for the

analysis of biased random walks repelled from zero see e.g.[38]).From the decrease of average size with decreasing p we deduce that the bias due to the singular extinctions has larger e?ect for smaller p ,i.e.if the new unit created in a speciation event has fewer links to the neighbors.

FIG.4.Distribution of number of units for di?erent values of p (△0.85,20.9,×0.95,+0.97,30.98).Data are averaged over 108time steps.Inset:Dependence of averaged number of units on p .The solid line corresponds to the power law n u ∝(1?p )?0.8.

FIG.5.Distribution of the number of units (full line)and connectivity (dashed line),for p =0.98,averaged over 108time steps.

B.Connectivity

In Fig.6we show the probability distribution of the connectivity of network sites P all (c )and distribution of connectivity of the extremal unit P extremal (c ).We can observe the tendency that the extremal unit has larger connectivity than average.This is in accord with the ?ndings of Ref.[16]obtained on static networks.It can be also easily understood intuitively.Indeed,in a mutation event the barriers of neighbors of the mutated unit are changed.So,the neighbors have enhanced probability to be extremal in the next time step.Therefore,the sites with higher number of neighbors have larger probability that a mutation occurs in their neighborhood and that they are then mutated in the subsequent step.

FIG.6.Distribution of the connectivity for all sites (full line)and for extremal sites only (dashed line),in the sta-tionary regime for p =0.98,averaged over 108time steps.Inset:Dependence of averaged connectivity on p .The solid line corresponds to the power law c ∝(1?p )?0.75.

The average connectivity c computed from the dis-tributions P all (c )is shown in the inset of Fig. 6.We can observe that analogically to the system size also the average connectivity diverges for p →1as a power law,but the value of the exponent is slightly di?erent.We ?nd c ∝(1?p )?αc with the exponent αc ?0.75.From the data available we were not able do decide,whether the exponents αn and αc are equal within the statistical noise.

In Fig.5we can see that also the distribution of con-nectivity has an exponential tail,similarly to the dis-tribution of network size.We measured also the joint probability density P (n u ,c )for the number of units and the connectivity.The result is shown as a contour plot in Fig.7.We can see that also for large networks (large n u )the most probable connectivity is small and nearly independent on n u .This means that the overall look of

the network created by the dynamics of our model is that there are a few sites with large connectivity,surrounded by many sites with low

connectivity.

FIG.7.Contour plot of the joint probability density P(n u,c)for number of units and connectivity,for p=0.8, averaged over3·109time steps.The contours correspond to

the following values of the probability density(from inside to outside):5·10?R,2·10?R,10?R,with orders R=3,4,5,6,7,

8. FIG.8.Distribution of connectivity for?xed number of units,for p=0.8and sizes n u=40(+),80(×),120(⊙),170 (2).The straight line is a power-law with exponent?2.3.

The data are the same as those used in Fig.7.

An interesting observation can be drawn from the re-sults shown in Fig.8.It depicts the joint probabil-ity density as a function of connectivity at?xed system sizes.We can see that for smaller system sizes,closer to the average number of units,the distribution is ex-ponential,while if we increase the system size a power-law dependence develops.For example for the system size?xed at n u=170we observe a power-law behavior P(n u,c)~c?ηnearly up to the geometric cuto?,c

This?nding may be in accord with the power-law distribution in growing networks[6,40].Indeed,in our model the power-law behavior applies only for networks signi?cantly larger than the average size.Such networks are created during time-to-time?uctuations leading to temporary expansion of the network.So,the power-law is the trace of expansion periods in the network evolu-tion,corresponding to continuous growth in the model of [6].The preferential attachment,which is the second key ingredient in[6]has also an analog in our model;highly connected units are more likely to be mutated,as was already mentioned in the discussion of Fig.6.However, here the preference of highly connected sites is a dynam-ical phenomenon,resulting from the extremal dynamics rules of our model.

C.Clusters

As noted already in the Sec.II,the network can be split into several disconnected clusters.The clusters can-not merge,but they may vanish due to extinctions.We observed qualitatively that after initial growth the num-ber of clusters exhibits stationary?uctuations around an average value,which increases when p approaches1.We measured both the distribution of the number of clusters and the distribution of their sizes.In Fig.9we show the distribution of the number of clusters.The most probable situation is that there is only a single cluster.However, there is a broad tail,which means that even large num-ber of clusters can be sometimes created.The tail has a power-law part with an exponential cuto?.The value of the exponent in the power-law regime P(n c)~n?ρc was aboutρ?1.2.We have observed that the width of the power-law regime is larger for larger p.This leads us to the conjecture that in the limit p→1the number of clusters is power-law distributed.

On the other hand,the distribution of cluster sizes shown in Fig.10has maximum at very small values. This is due to two e?ects.First,already the distribution of network size has maximum at small sizes,and second, if the network is split into many clusters,they have small size and remain unchanged for long time.The reason why small clusters change very rarely(and therefore can nei-ther grow nor disappear)can be also seen from Fig.10, where the distribution of sizes of the clusters contain-ing the extremal site is shown.The latter distribution is signi?cantly di?erent from the size distribution for all clusters and shows that the extremal site belongs mostly to large clusters.In fact,we measured also the fraction indicating how often the extremal unit is in the largest cluster,if there are more than one cluster.For the same

run from which the data shown in Fig.

10were collected,we found that this fraction is 0.97,i. e.very close to 1.A similar “screening e?ect”was reported also in the Cayley tree models [31]:the small isolated portions of the network are very stable and nearly untouched by the evolution.

FIG.9.Distribution of the number of clusters,for p =0.98.The straight line is a power law with exponent ?1.2.The data were averaged over 3independent runs,5·108,5·108,and 108time steps long.

FIG.10.Distribution of the cluster sizes s c for p =0.98,averaged over 108time steps.Full line -all clusters,dashed line -clusters containing the extremal site.Inset:Detail of the same distribution.

D.Mean distance

An important feature of a random network is also the

mean distance ˉd

between two sites,measured as mini-mum number of links,which should be passed in order to get from one site to the other.In D -dimensional lat-tices,the mean distance depends on the number of sites

N as ˉd

~N 1/D ,while in completely random networks the dependence is ˉd

~log N .In the small-world networks,the crossover from the former to the latter behavior is observed [8,9].

FIG.11.Dependence of the average distance of two sites within the same cluster on the cluster size,for p =0.95(full line)and p =0.97(dashed line),averaged over for 107time steps.In the inset we show the same data in the log-linear scale.

The dependence of the average distance within a clus-ter on the size of the cluster in our model is shown in

Fig.11.We can observe global tendency to decrease ˉd

when increasing p .This result is natural,because larger p means more links from a randomly chosen site and thus shorter distance to other sites.The functional form of the size dependence is not completely clear.However,for larger cluster sizes,greater than about 25,the de-pendence seems to be faster than logarithmic,as can be seen from the inset in Fig.11.So,the networks created in our model seem to be qualitatively di?erent from the random networks studied previously,as far as we know.

V.CONCLUSIONS

We studied an extremal dynamics model motivated by biological evolution on dynamically evolving random net-work.The properties of the model can be tuned by the parameter p ,the probability that a link is inherited in

the process of speciation.For p=1the model is self-organized critical and the average system size and con-nectivity grows without limits.Contrary to the usual BS model,we?nd two power-law regimes with di?erent exponents in the statistics of forwardλ-avalanches.The crossover avalanche size depends onλand diverges for λ→0as a power law.The reason why the criticalλis zero in this model is connected with the fact that time-averaged connectivity diverges for p=1.

We investigated the geometrical properties of the ran-dom networks for di?erent values of p.The average net-work size and average connectivity diverge as a power of 1?p.The probability distribution of system sizes has an exponential tail,which suggests that the dynamics of the system size is essentially a biased random walk with a re?ecting boundary,The value of the bias grows with decreasing p.The joint distribution of size and connec-tivity shows that even for large network sizes the most probable connectivity is low.Hence,there are few highly-connected sites linked to the majority of sites with small connectivity.Moreover,the situations where the sys-tem size is far above its mean value are characterized by power-law distribution of connectivity,like in the models of growing networks with preferential attachment.

The network can consist of several mutually discon-nected clusters.Even though the most probable situation contains only a single cluster,the distribution of clus-ter numbers has a broad tail,which shows a power-law regime with exponential cuto?.We observed the“screen-ing e?ect”,characterized by very small probability that the extremal site is found in any other cluster than the largest one.So,there is a central large cluster,where nearly everything happens,surrounded by some small peripheral clusters,frozen for the major part of the evo-lution time.

We measured also the mean distance measured along the links within one cluster.The distance grows very slowly with the cluster size;however,the increase seems to be faster than logarithmic.

Summarizing,we demonstrated that the extremal dy-namics,widely used in previous studies on macroevolu-tion in?xed-size systems is useful in creating random networks of variable size.It would be of interest to com-pare the properties of the networks created in our model with food webs and other networks found in the nature. For example the studies of food webs in isolated ecologies [4]give for network sizes about30average connectivities in the range from2.2to9,which is not in contradiction with the?ndings of our model.However,more precise comparisons are necessary for any reliable conclusions about real ecosystems.

ACKNOWLEDGMENTS

We wish to thank K.Sneppen, A.Markoˇs and A. P?e kalski for useful discussions.

[31]N.Vandewalle and M.Ausloos,J.Phys.I France5,1011

(1995).

[32]P.Bak,C.Tang,and K.Wiesenfeld,Phys.Rev.Lett.

59,381(1987).

[33]J.de Boer,B.Derrida,H.Flyvbjerg,A.D.Jackson,and

T.Wettig,Phys.Rev.Lett.73,906(1994).

[34]R.Ca?ero,P.De Los Rios,A.Valleriani,and J.L.Vega,

Phys.Rev.E60,R1111(1999).

[35]P.M.Gleiser,F.A.Tamarit,and S.A.Cannas,cond-

mat/9907084.

[36]R.V.Kulkarni, E.Almaas and D.Stroud,cond-

mat/9905066.

[37]A.-L.Barab′a si,R.Albert and H.Jeong,Physica A281,

69(2000).

[38]D.Sornette and R.Cont,J.Phys I France7,431(1997).

[39]D.Sornette,Phys.Rev.E57,4811(1998).

[40]S.N.Dorogovtsev,J.F.F.Mendes,and A.N.Samukhin,

cond-mat/0004434.

[41]S.N.Dorogovtsev and J. F. F.Mendes,cond-

mat/0001419.

[42]P.L.Krapivsky,S.Redner,and F.Leyvraz,cond-

mat/0005139.

[43]R.Albert and A.-L.Bar′a basi,cond-mat/0005085.

[44]S.N.Dorogovtsev and J. F. F.Mendes,cond-

mat/0005050.

[45]A.V′a zquez,cond-mat/0006132.

实验5 JAVA常用类

山西大学计算机与信息技术学院 实验报告 姓名学号专业班级 课程名称 Java实验实验日期成绩指导教师批改日期 实验5 JAVA常用类实验名称 一.实验目的: (1)掌握常用的String,StringBuffer(StringBuilder)类的构造方法的使用;(2)掌握字符串的比较方法,尤其equals方法和==比较的区别; (3)掌握String类常用方法的使用; (4)掌握字符串与字符数组和byte数组之间的转换方法; (5)Date,Math,PrintWriter,Scanner类的常用方法。 二.实验内容 1.二进制数转换为十六进制数(此程序参考例题249页9. 2.13) 程序源代码 import java.util.*; public class BinToHexConversion{ //二进制转化为十六进制的方法 public static String binToHex(String bin){ int temp; //二进制转化为十六进制的位数 if(bin.length()%4==0) temp = bin.length()/4; else temp = bin.length()/4 + 1; char []hex = new char[temp]; //十六进制数的字符形式 int []hexDec = new int[temp];//十六进制数的十进制数形式 int j = 0; for(int i=0;i=0&&dec<10) return (char)('0'+dec-0); else if(dec>=10&&dec<=15) return (char)('A'+dec-10); else return '@'; }

孙鑫深入详解MFC学习笔记

Windows编程 一、#define的几个注意点 ①#与##的用法; #xxx将后面的参数xxx字符串化 xxx##yyy,将两个参数连接 ②\的用法 一行结束使用,表示一行未结束。 二、函数调用约定_stdcall _stdcall是Pascal方式清理C方式压栈,通常用于Win32Api中,函数采用从右到左的压栈方式,堆栈由它自己清理。在win32应用程序里,宏APIENTRY,WINAPI,都表示_stdcall,非常常见。 相对应的_cdecl,堆栈由main()函数或者其他函数清理。 C和C++程序的缺省调用方式则为__cdecl,下图为VC++6.0的默认设置,因此在不显式写明调用约定的情况下,一般都是采用__cdecl方式,而在与Windows API打交道的场景下,通常都是显式的写明使用__stdcall,才能与Windows API保持一致。 另外,还要注意的是,如printf此类支持可变参数的函数,由于不知道调用者会传递多少个参数,也不知道会压多少个参数入栈,因此函数本身内部不可能清理堆栈,只能由调用者清理了。 三、防止头文件重复包含----预编译 在写好的类的首位加上预编译代码,例如: #ifndef xxx_h #define xxx_h Class xxx { ... }; #endif 四、HDC、CDC、CClientDC、CWindowDC HDC是平台SDK提供的全局类,与设备上下文相关 CDC则是类似于封装在CWnd中的一个HDC。 CClientDC:继承于CDC,构造函数完成获取DC,析构函数完成释放DC。 CWindowDC:继承于CDC,构造函数完成获取DC,析构函数完成释放DC,在整个窗口上绘图 CMetaFileDC:图元文件设备描述环境类 创建:CMetaFileDC dc; dc.Create(); 接下来用一般dc的绘图操作,绘图的内容均会保存至图元文件中; HMETAFILE m_hMetaFile=dc.Close();//图元文件赋予数据成员显示图元文件:用一般dc的PlayMetaFile(m_hMetaFile)显示图元文件 窗口销毁时删除图元文件 SDK函数::DeleteMetaFile(m_hMetaFile) 五、OnDraw函数、OnCreate函数 OnDraw函数:窗口重绘的时候被框架类FrameWnd调用,响应WM_PAINT消息。 OnCreate函数:窗口建立的时候调用的函数,响应WM_CREATE消息。

三角函数,反三角函数公式大全

三角函数公式 两角和公式 sin(A+B) = sinAcosB+cosAsinB sin(A-B) = sinAcosB-cosAsinB cos(A+B) = cosAcosB-sinAsinB cos(A-B) = cosAcosB+sinAsinB tan(A+B) = tanAtanB -1tanB tanA + tan(A-B) =tanAtanB 1tanB tanA +- cot(A+B) =cotA cotB 1-cotAcotB + cot(A-B) =cotA cotB 1 cotAcotB -+ 倍角公式 tan2A = A tan 12tanA 2 - Sin2A=2SinA?CosA Cos2A = Cos 2A-Sin 2A=2Cos 2A-1=1-2sin 2A 三倍角公式 sin3A = 3sinA-4(sinA)3 cos3A = 4(cosA)3-3cosA tan3a = tana ·tan(3π+a)·tan(3 π -a) 半角公式 sin( 2A )=2cos 1A - cos(2A )=2cos 1A + tan(2A )=A A cos 1cos 1+- cot(2 A )= A A cos 1cos 1-+ tan(2 A )=A A sin cos 1-=A A cos 1sin + 和差化积 sina+sinb=2sin 2b a +cos 2b a - sina-sinb=2cos 2b a +sin 2b a - cosa+cos b = 2cos 2b a +cos 2b a - cosa-cosb = -2sin 2b a +sin 2 b a - tanA+tanB=sin(A+B)/cosAcosB tanA-tanB=sin(A-B)/cosAcosB ctgA+ctgB=sin(A+B)/sinAsinB -ctgA+ctgB=sin(A+B)/sinAsinB 积化和差 sinasinb = - 21[cos(a+b)-cos(a-b)] cosacosb = 2 1 [cos(a+b)+cos(a-b)]

小白学Python笔记系列3.3.1 math库与random库

数学库及其使用 math库中常用的数学函数 函数数学表示含义 圆周率piππ的近似值,15位小数 自然常数e e e的近似值,15位小数 ceil(x) x 对浮点数向上取整 floor(x) x 对浮点数向下取整 pow(x,y)x y计算x的y次方 log(x)lg x以e为基的对数, log10(x)log10x以10为基的对数, sqrt(x)平方根 x

数学库及其使用 函数数学表示 含义exp(x)e的x次幂,degrees(x)将弧度值转换成角度radians(x)将角度值转换成弧度 sin(x)sin x 正弦函数cos(x)cos x 余弦函数tan(x)tan x 正切函数 asin(x)arcsin x 反正弦函数,x ?[-1.0,1.0]acos(x)arccos x 反余弦函数,x ?[-1.0,1.0]atan(x) arctan x 反正切函数,x ?[-1.0,1.0] math库中常用的数学函数

随机数库及其使用 random库中常用的函数 函数含义 seed(x)给随机数一个种子值,默认随机种子是系 统时钟 random()生成一个[0, 1.0)之间的随机小数 uniform(a,b)生成一个a到b之间的随机小数 randint(a,b)生成一个a到b之间的随机整数 randrange(a,b,c)随机生成一个从a开始到b以c递增的数 choice()从列表中随机返回一个元素 shuffle()将列表中元素随机打乱 sample(,k)从指定列表随机获取k个元素

随机数库及其使用 示例

JAVA中常用类的常用方法

JAVA屮常用类的常用方法 一.java?丨ang.Object 类 1、clone()方法 创建丼返M此对象的一个副木。要进行“克隆”的对象所属的类必须实现https://www.doczj.com/doc/0e13999128.html,ng. Cloneable 接口。 2、equals(Objectobj)方法 0 功能:比较引用类型数据的等价性。 0 等价标准.?引用类型比较引用,基木类型比较值。 0 存在特例.?对File、String、Date及封装类等类型来说,是比较类型及对象的内稃而+ 考虑引用的是否为同一实例。 3、finalize〇方法 当垃圾丨"丨收器确定>(、存在对该对象的更多引用时,由对象的垃圾丨"丨收器调用此方法。 4、hashCode〇方法返 回该对象的哈希码值。 5、notify〇方法 唤醒在此对象监视器上等待的中?个线祝。 6、notifyAII〇方法 唤醒在此对象监视器上等待的所有线程= 7、toString()方法 返W该对象的字符串表示。在进行String与其它类型数据的连接操作时,&动调用tostringo 方法。可以根据耑要重写toStringO方法。 8、wait()方法 在其他线程调用此对象的n〇tify()方法或notifyAIIO方法前,异致当前线程等待。 二、字符串相关类 I String 类 charAt(int index)返回指定索引处的char值。compareTo{String anotherString)按字

典顺序比较两个字符串。compareTolgnoreCase(Stringstr)按字典顺序比较两个字 符串,不考虑人小写。concat(String str)将指定字符串连接到此字符串的结尾。 endsWith(String suffix)测试此字符串是否以指定的〗?缀结束。equals{Object anObject)将此字符串与指定的对象比较。 equalslgnoreCase(String anotherString)将此String 与另一个String 比较,考虑人小'与’。indexOf(int ch)返H指定字符在此字符串屮第一次出现处的索引。 indexOf(String str)返回第一次出现的指定子字符串在此字符串屮的索引, lastlndexOf(intch)返回指定字符在此字符串中最后??次出现处的索引。 length()返|n丨此字符串的长度。 replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用newChar替换此字符串中出现的所有oldChar得到的。 split(String regex)根据给定正则表达式的匹配拆分此字符串。startsWith{String prefix)测试此字符 串是否以指定的前缀开始。substring(int beginlndex) 返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。 substring(int beginlndex, int endlndex) 返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的beginlndex 处开始,一直到索引endlndex-1处的字符。 t〇CharArray()将此字符串转换为一个新的字符数组。

CRichEditCtrl

CRichEditCtrl MFC Library Reference Using CRichEditCtrl(https://www.doczj.com/doc/0e13999128.html,/tie/7576199.html)rich edit控件是用户能够输入和编辑文本的窗口。文本能被指定字符和段落格式,并且也能包含嵌入式OLE对象。rich edit 控件在MFC中通过CRichEditCtrl类描绘。关于哪些你想知道更多?RichEdit控件概述 如果你在对话框中使用rich edit控件(不管你的程序是SDI,MDI,还是基本对话框),你必须在对话框显示之前调用AfxInitRichEdit一次。调用此函数的典型位置 在你的程序的InitInstance成员函数中。你不必每次显示对话框时调用它,仅仅第一次就可以了。如果你使用CRichEditView你不必调用 AfxInitRichEdit.Rich edit控件(CRichEditCtrl)为格式化文本提供程序接口。然而,一个程序必须实现任一用户接口组件,这个组件对于用户格式化操作可用是必要 的。那就是,Rich edit控件支持选定文本的字符或段落属性的改变。字符属性

的一些例子就是黑粗体,斜体,字体系列,和点大小。段落属性的例子如对齐,页边空白,和移字键 (英文原文:tab stops.表示在rich edit中按下tab键光标会移动一段距离)。然而,这是给你提供的用户接口,不管那是一个工具条按钮,菜单项,或是一个格式化字符对话框。也有函数对目 前选择查询richedit控件。使用这些函数显示当前属性设置,比如,设置一个选定标记在用户接口上,如果当前选择是黑粗体字符格式属性。参见CharacterFomatting和paragraph formatting查看更多字符段落格式化信息。rich edit控件支持几乎所有多行编辑控件( multiline edit controls)的操作和通知消息。因此,使用EDIT控件的应用程序很容易的变换为使用RICH EDIT控件。附加的消息和通知(notifications)能使程序访问richedit的其它特性。参看CEdit查看编辑控件消息。与rich edit控件有关的类 CRichEditView, CRichEditDoc, 和CRichEditCntrItem类提供在MFC的文档/视图结构环境内的RICH EDIT控件的功能。CRichEditView保持着文本和文本的格式化特性。CRichEditDoc保持着视图中OLE客户项的序列。CRichEditCntrItem提供对OLE客户项的container-side

反三角函数公式(完整)

反三角函数 分类 反正弦 反余弦 余弦函数x y cos =在]0[π,上的反函数,叫做反余弦函数。记作x cos arc ,表示一个 余弦值为x 的角,该角的范围在]0[π,区间内。定义域]11[, - , 值域]0[π,。 反正切 反余切 余切函数y=cot x 在)0(π,上的反函数,叫做反余切函数。记作x arc cot ,表示一个余切值为x 的角,该角的范围在)0(π,区间内。定义域R ,值域)0(π,。

反正割 反余割 运算公式 余角关系 2 arccos sin arc π = +x x 2 cot tan arc π =+x arc x 2 csc ec a π = +x arc x rcs 负数关系 x x sin arc )sin(arc -=- x x rc arccos )cos(a -=-π x x tan arc )tan(arc -=- x rc x c cot a )(ot arc -=-π

x rc x sec a )(arcsec -=-π x arc x c sec )(sc arc -=- 倒数关系 x arc x csc )1 arcsin(= x arc x sec )1 arccos(= x arc x arc x cot 2cot )1arctan(-==π x x x arc arctan 23arctan )1cot(-=+=ππ x x arc arccos )1 sec(= x x arc arcsin )1 csc(= 三角函数关系

加减法公式 1. ) 10,0()11arcsin(arcsin arcsin ) 10,0()11arcsin(arcsin arcsin ) 10()11arcsin(arcsin arcsin 22222 2 222222>+<<-+---=+>+>>-+--=+≤+≤-+-=+y x y x x y y x y x y x y x x y y x y x y x xy x y y x y x ,,或ππ 2. ) 10,0()11arcsin(arcsin arcsin ) 10,0()11arcsin(arcsin arcsin ) 10()11arcsin(arcsin arcsin 22222 2 222222>+><-----=->+<>----=-≤+≥---=-y x y x x y y x y x y x y x x y y x y x y x xy x y y x y x ,,或ππ 3. ) 0() 11arccos(2arccos arccos ) 0() 11arccos(arccos arccos 2 2 22<+----=+≥+---=+y x x y xy y x y x x y xy y x π 4. ) () 11arccos(arccos arccos ) () 11arccos(arccos arccos 2 2 22y x x y xy y x y x x y xy y x <--+=-≥--+-=- 5. ) 1,0(1arctan arctan arctan ) 1,0(1arctan arctan arctan ) 1(1arctan arctan arctan ><-++-=+>>-++=+<-+=+xy x xy y x y x xy x xy y x y x xy xy y x y x ππ

随机振动(振动频谱)计算(Random Vibration)

Random Vibration 1. 定义 1.1 功率谱密度 当波的频谱密度乘以一个适当的系数后将得到每单位频率波携带的功率,这被称为信号的功率谱密度(power spectral density, PSD)。 功率谱密度谱是一种概率统计方法,是对随机变量均方值的量度。 1.2 均方根 均方根(RMS)是指将N项的平方和除于N后,开平方的结果。均方根值也是有效值,如对于220交流电,示波器显示的有效值或均方根值为220V。 2. 加速度功率谱密度 2.1 单位 加速度单位:m/s^2或g 加速度功率谱密度单位:(m/s^2)^2/Hz或g^2/Hz Hz单位为:1/s, 所以加速度功率谱密度单位也可写为:m^2/s^3 2.2功率谱密度函数 功率谱密度函数曲线的纵坐标是(g2/Hz)。功率谱曲线下的面积就是随机加速度的总方差(g2): σ2= ∫Φ(f)df 其中:Φ(f)........功率谱密度函数 σ ............. 均方根加速度 3. 计算示例 随机振动100-2000HZ,功率谱密度为0.01g^2/Hz,则其加速度峰值计算如下: σ2=0.01*(2000-100)=19 σ=4.36g 峰值加速度不大于3倍均方根加速度:13.08g

4、SAE J 1455 随机振动要求 4.1功率谱图 4.1.1 Vertical axis 4.1.2 Transverse axis 4.1.3 Longitudinal axis

4.2 Vertical axis加速度计算 功率谱曲线下的面积:σ2=(40-5)0.016+0.5*(500-40)*0.016=4.24σ=2.06g 峰值加速度不大于3倍均方根加速度:6.18g 5. FGE随机振动要求 5.1功率谱图

《网络程序设计》复习题

1、什么叫套接字?套接字按通信性质可以分为哪两类? 2、理解线程的创建与使用方法,并能应用到程序设计中。 3、异构环境下的网络程序设计需要考虑哪些问题? 4、为什么在数据结构struct sockaddr_in中,成员变量sin_addr和sin_port需要转换为网络字节顺序,而sin_family不需要呢? 5、从网络编程的角度来简述和比较IP地址和端口的作用。 6、为什么网络编程时需要考虑字节顺序问题? 7、WinSock编程中需要哪些文件? 8、UDP程序的工作模型隐含着通信标识五元组的建立过程。这五元组在UDP的客户与服务端是由哪些函数分别确定的? 9、什么是阻塞与非阻塞通信?请解释两者的区别。 10、简述各种类型数据的发送与接收处理的方法。 11、简述基于UDP的客户机/服务器端socket编程流程。 12、什么是通信三元组和五元组?三元组和五元组每个元素在网络连接中起到什么作用? 13、为什么服务端在TCP通信过程中需要调用bind( )函数而客户端不需要?为什么客户机通常不需要绑定自己的端口号? 14、简述套接字Select模型原理,以及select模型的优势和不足。 15、简述阻塞模式服务器和客户端工作流程,以及阻塞模式套接字的优势和不足。 16、在实际应用中,很多TCP服务器程序在非正常退出时,如果立即重启服务器进程则会发生绑定服务器端口失败的错误,从而无法启动服务器进程,但等待一段时间后就可以了。为什么会发生这种情况呢?如何解决这个问题(或采取什么措施可以立即重启服务器进程)?(要求掌握setsockopt()函数的用法) 17、TCP程序的工作模型隐含着通信标识五元组的建立过程。这五元组在TCP的客户与服务端是由哪些函数分别确定的? 18、accept( )为什么要返回一个套接口?或者说,为什么要为每一个连接创建一个套接口来处理?UDP 服务器端为什么不需要多个套接口? 19、理解生产者-消费者模型,理解线程的同步与互斥方法(event和critical-section),并能应用到程序设计中。 20、采用阻塞式I/O模型时,套接字函数recv()的返回值有哪几种?分别对应什么情况? 21、closesocket()函数和shutdown()函数有何差别? 22、什么是TCP的三次握手机制?为什么要使用TCP的三次握手机制? 23、服务器端并发的两种模型及编程实现。 考试形式:闭卷 考试时间:120分钟 考试题型:选择题(2’×10=20’)、简答题(10’×6=60’)、程序设计题(20’)

4:一个经典的多线程同步问题汇总

一个经典的多线程同步问题 程序描述: 主线程启动10个子线程并将表示子线程序号的变量地址作为参数传递给子线程。子线程接收参数 -> sleep(50) -> 全局变量++ -> sleep(0) -> 输出参数和全局变量。 要求: 1.子线程输出的线程序号不能重复。 2.全局变量的输出必须递增。 下面画了个简单的示意图: 分析下这个问题的考察点,主要考察点有二个: 1.主线程创建子线程并传入一个指向变量地址的指针作参数,由于线程启动须要花费一定的时间,所以在子线程根据这个指针访问并保存数据前,主线程应等待子线程保存完毕后才能改动该参数并启动下一个线程。这涉及到主线程与子线程之间的同步。 2.子线程之间会互斥的改动和输出全局变量。要求全局变量的输出必须递增。这涉及到各子线程间的互斥。 下面列出这个程序的基本框架,可以在此代码基础上进行修改和验证。 //经典线程同步互斥问题 #include #include #include long g_nNum; //全局资源 unsigned int__stdcall Fun(void *pPM); //线程函数 const int THREAD_NUM = 10; //子线程个数 int main() { g_nNum = 0;

HANDLE handle[THREAD_NUM]; int i = 0; while (i < THREAD_NUM) { handle[i] = (HANDLE)_beginthreadex(NULL, 0, Fun, &i, 0, NULL); i++;//等子线程接收到参数时主线程可能改变了这个i的值} //保证子线程已全部运行结束 WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE); return 0; } unsigned int__stdcall Fun(void *pPM) { //由于创建线程是要一定的开销的,所以新线程并不能第一时间执行到这来int nThreadNum = *(int *)pPM; //子线程获取参数 Sleep(50);//some work should to do g_nNum++; //处理全局资源 Sleep(0);//some work should to do printf("线程编号为%d 全局资源值为%d\n", nThreadNum, g_nNum); return 0; } 运行结果:

常用反三角函数公式表

反三角函数公式

反三角函数图像与特征 1 :

反三角函数的定义域与主值范围 式中n为任意整数.

反三角函数的相互关系 sin x = x-x3/3!+x5/5!-...(-1)k-1*x2k-1/(2k-1)!+... (-∞= -1 And x < -0.5 Then ArcSin = -Atn(Sqr(1 - x * x) / x) - 2 * Atn(1) If x >= -0.5 And x <= 0.5 Then ArcSin = Atn(x / Sqr(1 - x * x))

If x > 0.5 And x <= 1 Then ArcSin = -Atn(Sqr(1 - x * x) / x) + 2 * Atn(1) End Function ArcCos(x) 函数 功能:返回一个指定数的反余弦值,以弧度表示,返回类型为Double。 语法:ArcCos(x)。 说明:其中,x的取值范围为[-1,1],x的数据类型为Double。 程序代码: Function ArcCos(x As Double) As Double If x >= -1 And x < -0.5 Then ArcCos = Atn(Sqr(1 - x *x) / x) + 4 * Atn(1) If x >= -0.5 And x <= 0.5 Then ArcCos = -Atn(x/ Sqr(1 - x * x)) + 2 * Atn(1) If x> 0.5 And x <= 1 Then ArcCos = Atn(Sqr(1 - x*x) / x) End Function

java随机函数用法Random

java随机函数用法Random import java.util.Random; public class RandomNumber{ public static void main(String[] args) { // 使用https://www.doczj.com/doc/0e13999128.html,ng.Math的random方法生成随机数System.out.println("Math.random(): " + Math.random()); // 使用不带参数的构造方法构造java.util.Random对象System.out.println("使用不带参数的构造方法构造的Random对象:"); Random rd1 = new Random(); // 产生各种类型的随机数 // 按均匀分布产生整数 System.out.println("int: " + rd1.nextInt()); // 按均匀分布产生长整数 System.out.println("long: " + rd1.nextLong()); // 按均匀分布产生大于等于0,小于1的float数[0, 1) System.out.println("float: " + rd1.nextFloat());

// 按均匀分布产生[0, 1)范围的double数 System.out.println("double: " + rd1.nextDouble()); // 按正态分布产生随机数 System.out.println("Gaussian: " + rd1.nextGaussian()); // 生成一系列随机数 System.out.print("随机整数序列:"); for (int i = 0; i < 5; i++) { System.out.print(rd1.nextInt() + " "); } System.out.println(); // 指定随机数产生的范围 System.out.print("[0,10)范围内随机整数序列: "); for (int i = 0; i < 10; i++) { // Random的nextInt(int n)方法返回一个[0, n)范围内的随机数 System.out.print(rd1.nextInt(10) + " "); } System.out.println(); System.out.print("[5,23)范围内随机整数序列: "); for (int i = 0; i < 10; i++) {

Java常用类库介绍

教学内容 第七讲Java常用类库介绍 7.1 Java类库的结构 类库就是Java API(Application Programming Interface,应用程序接口),是系统提供的已实现的标准类的集合。在程序设计中,合理和充分利用类库提供的类和接口,不仅可以完成字符串处理、绘图、网络应用、数学计算等多方面的工作,而且可以大大提高编程效率,使程序简练、易懂。 Java类库中的类和接口大多封装在特定的包里,每个包具有自己的功能。表7.1列出了Java中一些常用的包及其简要的功能。其中,包名后面带“. *”的表示其中包括一些相关的包。有关类的介绍和使用方法,Java中提供了极其完善的技术文档。我们只需了解技术文档的格式就能方便地查阅文档。 表7.1Java提供的部分常用包 注:在使用Java时,除了https://www.doczj.com/doc/0e13999128.html,ng外,其他的包都需要import语句引入之后才能使用。 7.2 https://www.doczj.com/doc/0e13999128.html,ng包中的常用类

https://www.doczj.com/doc/0e13999128.html,ng是Java语言最广泛使用的包。它所包括的类是其他包的基础,由系统自动引入,程序中不必用import语句就可以使用其中的任何一个类。https://www.doczj.com/doc/0e13999128.html,ng中所包含的类和接口对所有实际的Java程序都是必要的。下面我们将分别介绍几个常用的类。 7.2.1 String类和StringBuffer类 许多语言中,字符串是语言固有的基本数据类型。但在Java语言中字符串通过String类和StringBuffer类来处理。 1.String类 Java语言中的字符串属于String类。虽然有其它方法表示字符串(如字符数组),但Java使用String 类作为字符串的标准格式。Java编译器把字符串转换成String对象。String对象一旦被创建了,就不能被改变。如果需要进行大量的字符串操作,应该使用StringBuffer类或者字符数组,最终结果可以被转换成String格式。 (1)创建字符串 创建字符串的方法有多种方式,通常我们用String类的构造器来建立字符串。表6.2列出了String 类的构造器及其简要说明。 表7.2 String类构造器概要 【例7.1】使用多种方法创建一个字符串并输出字符串内容。 public class StrOutput { public static void main(Sring[] args) { //将字符串常量作为String对象对待,实际上是将一个String对象赋值给另一个 String s1 = "Hello,java!"; //声明一个字符串,然后为其赋值 String s2; s2 = "Hello,java!";

CSerialPort类解析

CserialPort类的功能及成员函数介绍 CserialPort类是免费提供的串口类,Codeguru是一个非常不错的源代码网站CserialPort类支持线连接(非MODEM)的串口编程操作。 CserialPort类是基于多线程的,其工作流程如下:首先设置好串口参数,再开启串口检测工作线程,串口检测工作线程检测到串口接收到的数据、流控制事件或其他串口事件后,就以消息方式通知主程序,激发消息处理函数来进行数据处理,这是对接受数据而言的,发送数据可直接向串口发送。 介绍几个经常用到的函数: 1、串口初始化函数InitPort 这个函数是用来初始化串口的,即设置串口的通信参数:需要打开的串口号、波特率、奇偶校验方式、数据位、停止位,这里还可以用来进行事件的设定。如果串口初始化成功,就返回TRUE,若串口被其他设备占用、不存在或存在其他股占,就返回FALSE,编程者可以在这儿提示串口操作是否成功如果在当前主串口调用这个函数,那么pPortOwner可用this指针表示,串口号在函数中做了限制,只能用1,2,3和4四个串口号,而事实上在编程时可能用到更多串口号,可以通过通过注释掉本函数中“assert(portur>0&&portnr<5)”语句取消对串口号的限制。 if (m_ComPort[0].InitPort(this,1,9600,'N',8,1,EV_RXFLAG | EV_RXCHAR,512)) //portnr=1(2),baud=9600,parity='N',databits=8,stopsbits=1,

//dwCommEvents=EV_RXCHAR|EV_RXFLAG,nBufferSize=512 { m_ComPort[0].StartMonitoring(); //启动串口监视线程 SetTimer(1,1000,NULL); //设置定时器,1秒后发送数据} e lse { CString str; str.Format("COM1 没有发现,或被其它设备占用"); AfxMessageBox(str); } 2、启动串口通信监测线程函数StartMonitoring() 串口初始化成功后,就可以调用BOOL StartMonitoring()来启动串口检测线程,线程启动成功,返回TRUE。 BOOL CSerialPort::StartMonitoring() { if (!(m_Thread = AfxBeginThread(CommThread, this))) return FALSE; TRACE("Thread started\n"); return TRUE; } 注意这个函数一旦调用,就会建立一个线程,这个线程一直不会结束,调用StopMonitoring ()只是将这个线程挂起。 3、暂停或停止监测线程函数StopMonitoring() 该函数暂停或停止串口检测,要注意的是,调用该函数后,串口资源仍然被占用 // // Suspend the comm thread // BOOL CSerialPort::StopMonitoring() { TRACE("Thread suspended\n"); m_Thread->SuspendThread(); return TRUE; } 4、关闭串口函数ClosePort() 该函数功能是关闭串口,释放串口资源,调用该函数后,如果要继续使用串口,还需要调用InitPort()函数。 这里有一个问题,在以前的版本中,如果调用了StartMonitoring函数,关闭串口后,再打开就会出现问题,及网上所说的关闭死锁问题。找了大量资料后,

引用java中随机函数的使用

引用java中随机函数的使用 引用 axunlb的java中随机函数的使用 java中随机函数的使用 Random N = new Random(1000);中的1000产生的随机数在0到1000之间,参数用于指定随机数产生的范围 方法1 (数据类型)(最小值+m()*(最大值-最小值+1)) 例: (int)(1+m()*(10-1+1)) 从1到10的int型随数 方法2 获得随机数 for (int i=0;i<30;i++) {.println((int)(1+m()*10));} (int)(1+m()*10) 通过包的random方法得到1-10的int随机数 公式是:最小值---最大值(整数)的随机数

(类型)最小值+m()*最大值 方法3 Random ra =new Random(); for (int i=0;i<30;i++) {.println(ra.nextInt(10)+1);} 通过包中的Random类的nextInt方法来得到1-10的int随机数import .*; class Test { public static void main(String args[]) { int[] t = new int[10]; Random rand = new Random(); for(int i=0;i

} } } java中Random的构造函数Random()中默认的种子就是当前时间和midnight, January 1, 1970 UTC的差值(用毫秒计),所以每次运行程序都可以得到不同的结果nt()也可以如此用r.nextInt(100)—–100以内的随机数

JAVA中常用类的常用方法

JAVA中常用类的常用方法 一、类 1、clone()方法 创建并返回此对象的一个副本。要进行“克隆”的对象所属的类必须实现. Cloneable接口。 2、equals(Object obj)方法 功能:比较引用类型数据的等价性。 等价标准:引用类型比较引用,基本类型比较值。 存在特例:对File、String、Date及封装类等类型来说,是比较类型及对象的内容而不考虑引用的是否为同一实例。 3、finalize()方法 当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。 4、hashCode()方法返回该对象的哈希码值。 5、notify()方法唤醒在此对象监视器上等待的单个线程。 6、notifyAll()方法唤醒在此对象监视器上等待的所有线程。 7、toString()方法 返回该对象的字符串表示。在进行String与其它类型数据的连接操作时,自动调用toString()方法。可以根据需要重写toString()方法。 8、wait()方法 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。

二、字符串相关类 l String类 charAt(int index) 返回指定索引处的 char 值。 compareTo(String anotherString) 按字典顺序比较两个字符串。compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。concat(String str) 将指定字符串连接到此字符串的结尾。 endsWith(String suffix) 测试此字符串是否以指定的后缀结束。 equals(Object anObject) 将此字符串与指定的对象比较。 equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。 indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。 indexOf(String str) 返回第一次出现的指定子字符串在此字符串中的索引。lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。length() 返回此字符串的长度。 replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 split(String regex) 根据给定正则表达式的匹配拆分此字符串。 startsWith(String prefix) 测试此字符串是否以指定的前缀开始。 substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。

C多线程编程实例实战

C#多线程编程实例实战 问题的提出 所谓单个写入程序/ 多个阅读程序的线程同步问题,是指任意数量的线程访问共享资源时,写入程序(线程)需要修改共享资源,而阅读程序(线程)需要读取数据。在这个同步问题中,很容易得到下面二个要求: 1 )当一个线程正在写入数据时,其他线程不能写,也不能读。 2 )当一个线程正在读入数据时,其他线程不能写,但能够读。在数据库应 用程序环境中经常遇到这样的问题。比如说,有n 个最终 用户,他们都要同时访问同一个数据库。其中有m个用户要将数据存入数据库,n-m 个用户要读取数据库中的记录。 很显然,在这个环境中,我们不能让两个或两个以上的用户同时更新同一条记录,如果两个或两个以上的用户都试图同时修改同一记录,那么该记录中的信息就会被破坏。 我们也不让一个用户更新数据库记录的同时,让另一用户读取记录的内容。因为读取的记录很有可能同时包含了更新和没有更新的信息,也就是说这条记录是无效的记录。 实现分析 规定任一线程要对资源进行写或读操作前必须申请锁。根据操作的不同,分为阅读锁和写入锁,操作完成之后应释放相应的锁。将单个写入程序/ 多个阅读程序的要求改变一下,可以得到如下的形式: 一个线程申请阅读锁的成功条件是:当前没有活动的写入线程。 一个线程申请写入锁的成功条件是:当前没有任何活动(对锁而言)

的线程 因此,为了标志是否有活动的线程,以及是写入还是阅读线程,引入一个变量m_nActive ,如果m_nActive > 0 ,则表示当前活动阅读线程的数目,如果 m_nActive=0 ,则表示没有任何活动线程,m_nActive <0 ,表示当前有写入线程在活动,注意m_nActive<0 ,时只能取-1 的值,因为只允许有一个写入线程活动。 为了判断当前活动线程拥有的锁的类型,我们采用了线程局部存储技术(请参阅其它参考书籍) ,将线程与特殊标志位关联起来。 申请阅读锁的函数原型为:public void AcquireReaderLock( int millisecondsTimeout ) ,其中的参数为线程等待调度的时间。函数定义如下:public void AcquireReaderLock( int millisecondsTimeout ) { // m_mutext 很快可以得到,以便进入临界区m_mutex.WaitOne( ); // 是否有写入线程存在 bool bExistingWriter = ( m_nActive < 0 ); if( bExistingWriter ) { // 等待阅读线程数目加1, 当有锁释放时,根据此数目来调度线程 m_nWaitingReaders++; } else { // 当前活动线程加1 m_nActive++; } m_mutex.ReleaseMutex();

相关主题
文本预览
相关文档 最新文档