text:
# How far is the relativistic star?

1. Dec 1, 2011

### PatrickPowers

1. The problem statement, all variables and given/known data

Using natural units with c=1. We have our Sun and a star at rest relative to it one light year away. A space ship travels from our Sun to the star with v=1/2. During the journey how much time passes on the space ship's clock? How much distance does the captain of the space ship think has been traveled during the journey?

2. Relevant equations

-1 < v < 1

t' = gamma(t - vx)
x' = gamma(x - vt)
y' = y
z' = z

gamma = 1/sqrt(1-v^2)

3. The attempt at a solution

In the Sun's frame the star is at (0,1), and the space ship will reach the star at (2,1).
To get the space ship's view of the amount of time passed, we perform the Lorentz transform on (2,1).

t'=gamma(2-1/2)
x'=gamma(1-1)=0
y=0
z=0
gamma=1/sqrt(3/4)=sqrt(4/3)

So by the ship's clock the space ship has reached the star in sqrt(4/3)*3/2=sqrt(4/3)*sqrt(9/4)=sqrt(3). That seems reasonable.

How about the distance the ship's captain believes have been traveled. At t=t'=0 the star is at t=0 x=1. So if we perform the Lorentz transform on this we should get the distance perceived in the moving frame.

t' = gamma(0 - 1/2)
x' = gamma(1)
y' = 0
z' = 0

so x'=sqrt(4/3) which is greater than one. That seems unphysical to me. But the captain will calculate his velocity as gamma/(gamma3/2) = 2/3 which seems reasonable.

As a check I redid the problem with v=0.9 and the captain calculates his velocity as 4.73 which seems unphysical. What am I doing wrong?

2. Dec 2, 2011

### <NAME>

Star is 1ly away in Star frame - ship travels at 0.5c so it takes two years to get there.

$\gamma = 1/\sqrt{1-0.5^2} = 2/\sqrt{3}$ which you got well done.

Everybody agrees the ships clock reads $\Delta t = 2/\gamma = \sqrt{3}yr$ (well done) when it reaches the star, even though 2yrs have passed in the star frame. But in the ship POV this is fine because the star was only $d=v\Delta t$ away - so of course it took less time to draw close.

You see - moving lengths are contracted ... and as far as the captain is concerned, the stars are the ones moving.

3. Dec 2, 2011

### D H

Staff Emeritus

The above is your error. What you are doing here is calculating the x coordinate of the spaceship in the spaceship frame. Think about it for a second: What is the spaceship's position with respect to itself?

What you need to do is to
• Calculate the target star's position in spaceship frame coordinates at start of the journey (t=t'=0). This yields the distance the spaceship will travel in spaceship coordinates, or
• Calculate the sun's position in spaceship frame coordinates at the time the spaceship reaches the target star. This yields the distance the spaceship has traveled in spaceship coordinates.

4. Dec 2, 2011

### latentcorpse

Not quite.

The moving clock should be running slow.

It certainly takes 2 years from the perspective of the Sun.

Therefore the captain (who's moving) should see it take more than 2 years.

The formula is $\Delta t = \frac{t}{\sqrt{1-\frac{v^2}{c^2}}}=\gamma t$

which in this case means the captain sees it take $\Delta t = \frac{4}{\sqrt{3}}$ years.

5. Dec 2, 2011

### D H

Staff Emeritus
The √3 years is correct. If the captain's spaceship is fast enough (0.5 c isn't even close to fast enough), the captain could make it to the Andromeda galaxy within her lifetime even though the galaxy is 2.5 million light years away -- to us, that is.

6. Dec 2, 2011

### latentcorpse

I've seriously confused myself haha!

Moving clocks run slow. Does that mean that the captain sees it take 2 years because he isn't moving with respect to the spaceship clock (i.e. both him and the spaceship clock are on the spaceship and so have no movement relative to one another).

However, from the perspective of someone fixed at our Sun, they see the spaceship clock start to run slow because it is moving i.e. they will observe time dilation.

The formula for time dilation is t' = gamma * t and gamma is definitely root(3)/2 so why isn't it 4/root(3)?

Thanks.

7. Dec 3, 2011

### <NAME>

I used to be confused by that "moving clocks run slow" saying all the time... and finally got it by remembering which twin gets to be younger.

A clock is slow in the sense that it's hands are moving slower ... so, after a while, the time it shows lags behind. Slow right?

It helps if you draw the space-time diagrams.
For some reason nobody likes to draw the wee pictures these days.
Everyone wants to plug numbers into equations.

8. Dec 3, 2011

### D H

Staff Emeritus
No, it means the captain sees that that the journey takes less than 2 years.
You are forgetting that from the perspective of someone on the moving spaceship, it is the Earth clocks that are running slow. This is one of those seemingly paradoxical aspects of special relativity: A says B's clock is running slow while B says that it is A's clock that is running slow.

So, how to solve this particular problem? There a lot of ways to look at it, and all will give the same answer: The captain's clock indicate that the trip takes √3 years. One way is via the Lorentz transform, as was done in the original post. Another way is to divide the length-contracted distance by the velocity. From the captain's POV, the target star is initially at a distance of (√3)/2 light years (not one light year) and is moving toward the stationary spaceship at 0.5 c. d/v=(0.5√3 light years)/(0.5 light years/year) = √3 years.

9. Dec 3, 2011

### latentcorpse

So surely the captain doesn't see the ship clock run slow since he is in the ship frame and so he sees the clock on Earth run slow.

Meanwhile, the clock on Earth takes two years and it is the observer on Earth who thinks that the captains clock is running slow and taking \root(3) years.

Yes?

Disclaimer: It's been a long time since I did this and I seem to have forgotten it!

10. Dec 3, 2011

### D H

Staff Emeritus
The captain indeed does not see her clock as running slow. To her, her clock is working just fine. (Glance at the clock and then count: One thousand one, one thousand two, one thousand three, ... one thousand sixty. Glance at the clock again: One minute!)

She also sees the target star as coming toward her at 0.5c, easily verified by looking at the blueshift of the hydrogen alpha line. She also sees that the target star is initially at a distance of √3/2 light years (not 1 light year). This initial distance is a calculated value, but is easily confirmed by measurement by observing the increase in apparent magnitude as the spaceship approaches the target star.

These measurements are confirmed when the spaceship flies by the target star √3 years later.

11. Dec 4, 2011

### Simon Bridge

Lets be careful here - to use Special Relativity, the ship has to fly past both stars ... it does not start at one and end at the other (that would require acceleration).

If we prepare the stars so there are two clocks in the star-frame, one at Sol and the other at The Destination, which are synchronized, then - as Sol passes the Captain, she looks out and notes the time on the Sol clock and on her own. When the Destination passes, she looks out again, noting both times.

I think what LatentCorpse is wondering is this:

In the captains POV
Speed of the stars is 0.5c
The trip-time on the ship clock was √3yrs
Distance between the stars was √3/2ly
The stars are moving - therefore the star-clock trip time is √3/γ = 1.5yrs.

So following the above,
The stars should be only 0.75ly apart from the POV of the star-frame.

See how easy it is to get messed up with this?

My fav description is this one... it's geometric and I like geometry. Especially the bits with space-time diagrams: probably the clearest way to sort these ideas out.

12. Dec 4, 2011

### D H

Staff Emeritus
There's nothing wrong with acceleration in special relativity, so long as it's not gravitational acceleration. The only thing that special relativity can't handle is gravitation.

13. Dec 4, 2011

### latentcorpse

So the captain genuinely sees root(3) years elapse on her clock. This is because
(i) Her clock is running fine i.e. she's not moving in her frame so her proper time is equal to coordinate time
(ii) The star is moving towards her at 0.5c and so the initial distance undergoes length contraction
(iii) t=s/v and if s is length contracted i.e. less then t is less

What about from the perspective of someone at the initial star. They see root(3) years elapse on spaceship clock because:
(i) Both target and initial start remain a fixed distance of 1 light year apart throughout the experiment
(ii) Spaceship is flying at 0.5c and so they see time dilation on the spaceship clock
(iii) t=s/v = 1/0.5 =2 gives the coordinate time elapsed for the journey
(iv) we put this into the lorentz transformation and see that root(3) of a year is actually elapsed

What about from the perspective of someone at the target star? This will be the exact same argument as above.

If you can confirm that all of that is fine then my last concern is how this plays out physically. Consider the following incorrect argument

Taking the captain and an observer at the initial star:
(i) It takes root(3) years for the captain to reach the target
(ii) The observer at star see it take 2 years
Obviously this is due to special relativistic effects but could we relate it to the time the light takes to travel back to the initial start?

i.e. spaceship arrives after root(3) years
it takes 2-(root(3)) years for light to travel back to initial star
therefore observer at initial start sees spaceship arrive after 2 years

this argument doesn't work seeing as they are using genuinely different clocks. Is it in fact true to say that the observer at the initial star "CALCULATES" the journey of the spaceship will take 2 years but would in fact actually have to wait much, much longer to see the arrival. In fact, they would have to wait another 2 years for the light to travel back to them

Finally, suppose the spaceship comes to a halt at target star. This necessitates a deceleration - will this deceleration cause time to essentially "catch up" and realign the spaceship clock with the clock of an observer at the initial star? If so, how does this work?

Thanks a lot for your help.

14. Dec 4, 2011

### D H

Staff Emeritus
Everything you typed before that looks fine.

Yes, you could. What the different observers see (as opposed to calculate) is my personal favorite explanation of the twin paradox. It appeals to me. Different explanations appeal to others; it doesn't really matter which explanation is used so as they all yield the same answer.

Suppose the captain sends a time-stamped video signal back to Earth just as she arrives at the target star. Per the ship's clock, the journey to the target stars takes but √3 (~ 1.732) years. The signal sent back to Earth will have a time stamp of journey start time + 1.732 years, with the captain's apparent age being in agreement with this time stamp. After correcting for the time it took for this signal to reach Earth, the Earth observers will see this as a confirmation of relativity. Her 1.732 years multiplied by her gamma (2/√3) is exactly equal to 2/3 * 3 years.

I'll anticipate the remark "But wait! The captain should see the Earth-bound clocks as dilated!" Suppose the Earth sends a congratulatory message to the captain. They send this message a year (a year as measured on the Earth, that is) after the start of the journey so that reception of the message coincides with the captain's arrival at the target star. The signal will have a time stamp journey start time + 1 year, with the captain's cohorts' apparent ages being in agreement with this time stamp. After correcting for the time it took for this signal to reach the spaceship, the captain will see this as a confirmation of relativity. Their 1 year multiplied by their gamma (2/√3) is exactly equal to 2/3 * √3 years.

That won't happen. It is velocity and velocity only (i.e., not acceleration or any higher order derivative) that causes time dilation. This is the clock hypothesis, and it has been tested time and time again.

Suppose that the spaceship starts on a return journey to Earth after making a brief stop at the target star. Ignoring the time spent at the target star, the captain will have aged a total of 3.464 years, but her Earth-bound will have aged 4 years. This is the twin paradox. There are lots and lots of web pages that describe this phenomenon.

15. Dec 4, 2011

### Simon Bridge

However - if the captain started from Sol and stopped at the Destination star, that would change the math we've been doing.

16. Dec 5, 2011

### latentcorpse

I don't get what you are doing here. Looking at your first paragraph. You have the captain sending the message after ~1.7 years.
The light takes 1 year to reach Earth
Surely it is the 1 year that we have to Lorentz transform (giving 1* 2/root(3) = 2/root(3))
And so the video message would be received on Earth ~1.7+2/root(3) years later, no?

Where am I going wrong in my understanding?

So the captain is genuinely younger? Or is this just from the perspective of the Earth observer?

Surely then, seeing as we said that from the captain's frame the clocks on Earth run slow, the captain will see the Earth observer as being younger than her when she returns?

17. Dec 5, 2011

### D H

Staff Emeritus
What you are doing wrong is that you are mixing and matching frames without realizing it.

Let's start with Newtonian universe. The spaceship travels the 1 light year distance at 0.5c. From the perspective of an Earth-bound observer, the outward journey takes two years, and the signal announcing the arrival at the target takes another year to return to Earth. So, three years total pass from launch to reception of the arrival signal. In this Newtonian universe, the time stamp on that signal is 2 years mission elapsed time (MET).

Now let's go to our relativistic universe. From the perspective of an Earth-bound observer, the outward journey still takes two years, and the signal announcing the arrival at the target still takes another year to return to Earth. There is no difference between our universe and the Newtonian universe in this regard. Our universe and the Newtonian one depart when it comes to the time stamp on that announcement message. It's 2 years MET in the Newtonian universe, but only 1.732 years MET in our relativistic universe.

The captain is definitely younger on return than her Earth-bound cohorts. I suggest you google "twin paradox". You'll find plenty of explanations on the 'net, including several discussions right here at this site.

18. Dec 5, 2011

### latentcorpse

Got it I think.
And the light takes the same time in both universes because it travels on null geodesics and these are immune to the effects of relativity i.e. c is the universal speed limit and can't be changed regardless of frame of reference?

Captain is definitely younger. From perspective of Earthling, this is because she is moving at a velocity close to speed of light and therefore spaceship clock will run slow i.e. less time will elapse and so it takes her 1.7 years to get there and 1.7 years back i.e. she is 3.4 years older whilst Earthling has aged 4 years.

What about from captain's perspective? Well her clock is running fine (from her perspective at least). However, she is travelling at 0.5c and so there will be some length contraction at play. In fact she will have a shorter journey at the same speed and so less time will elapse. In fact, only 1.7 years will elapse in each direction. Again, she returns to Earth having aged only 3.4 years whilst the Earthling has aged 4(*)

Is this all correct? I think it is!

The only bit I don't get is the (*) bit at the end of the last paragraph I wrote. From the captain's frame of reference it is the Earth that is receeding at 0.5c and so surely she should see Earth clocks undergo time dilation. From this perspective, less time should elapse on Earth clocks and in fact the Earthling should age 3.4 also instead of 4 years.

To sum up, I think I've got it all except the Earth time from captain's perspective!

19. Dec 5, 2011

### D H

Staff Emeritus
The key to understanding the twin paradox is to realize that the spaceship turns around. If the spaceship didn't turn around, you would instead have the seeming paradox that the captain and her Earth-bound cohorts each see the other's clock as running slow.

Before explaining the twin paradox yet again, try reading this post that discusses a spaceship traveling at 0.8c to a star 16 light years away: [post]2696480[/post].

20. Dec 5, 2011

### latentcorpse

Hi again.

That's a good explanation but....

(i) Are you assuming the transmission of signals between A and B is instantaneous? Presumably so otherwise a signal sent upon birth of A's child 4 years after take off wouldn't arrive at target start until 18 years have elapsed by A's calculation (4+9.6=13.6 years by B's calculation).

(ii) How can there ever be any speeding up of clocks?
The Lorentz transformation is $\Delta t = \sqrt{1-\frac{v^2}{c^2}} t$ and since $v \leq c$, we have that $\Delta t \geq t$ always. So it appears to me that we are only able to generate time dilations not speeding up of clocks?


text:
## segunda-feira, 28 de novembro de 2011

### Broken Arrow - O acidente de Palomares - Introdução

 Um KC-135 reabastacendo um B-52D. Várias coisas podem dar errado...

17 de Janeiro de 1966: um bombardeiro B-52G, carregando quatro bombas de hidrogênio Mk48, colide com o avião tanque KC-135 a 31.000 pés de altitude, durante uma operação de reabastecimento no ar, sobre a Espanha.

Apesar do foco deste blog ser a Segunda Guerra Mundial, venho trazer a história do Acidente de Palomares, um dos pontos altos da Guerra Fria.

Introdução

Para compreendermos bem as implicações deste acidentes, precisamos antes nos remeter para o fim da Segunda Guerra Mundial, principalmente para dois eventos: o bombardeio de Tóquio e as bombas de Hiroshima e Nagasaki.

Durante a SGM, não havia nos Estados Unidos, a força aérea como um braço independente, havendo apenas o Exército e a Marinha compondo as Forças Armadas americanas. Desta forma, a aviação de guerra era vinculada principalmente ao Exército, através da USAAF - United States Army Air Force.

Com a detonação das bombas atômicas sobre o Japão, uma nova e revolucionária arma foi apresentada. Destruir uma cidade com uma bomba, ao invés de vários bombardeios e dezenas de raids, era - e ainda é - uma vantagem estratégica indescritível. E nos altos escalões militares americanos começou a discussão sobre qual Força deveria ter a posse desta nova arma de destruição absoluta.

Considerando a dimensão e peso das primeiras bombas, desenvolvidas com o Projeto Manhattan, em Los Alamos, a única forma prática de utilização dessas bombas era através de aeronáveis especialmente desenvolvidas para este fim, suportando o peso das bombas com condições táticas de detonação e retorno seguro.

Aliado a isto, a eficiência da USAAF foi claramente demonstrada com o  bombardeio de Tóquio em Abril de 1942. Apesar de pequeno no número de aeronaves, este bombardeio trouxe a capital inimiga às chamas, dado a eficiência da utilização de B-29 em voos de baixa altitude, carregando grandes quantidades de bombas incendiárias, alijadas sobre uma cidade feita de madeira.

As consequências deste bombardeio foi ajudar com encurtamento da Guerra (finalizada com as bombas atômicas), e o reconhecimento da eficiência da Força Aérea com força independente de guerra, não se limitando apenas ao suporte de operações de solo ou marinhas.

Com a nova arma podendo ser aplicada de forma tática somente por aviões, e a demostração prática da eficiência de uma Força Aérea, foi criada a terceira força americana: a USAF - United States Air Force, criada em 18 de setembro de 1948, tendo como homem forte <NAME>, condutor do bombardeio de Tóquio.

Dentro da recém-criada USAF, o comando que mais ganhou força e destaque durante a Guerra Fria foi o SAC - Strategic Air Command, tornando-se o braço mais forte da USAF.

O SAC foi criado com a missão principal de prover a capacidade de bombardear alvos em qualquer parte do mundo (leia-se "União Soviética" e seus satélites). Apesar de seu importante objetivo, o SAC em seus primeiros dois anos existiu apenas no papel, devido ao movimento de desmobilização com o fim da SGM e a insatisfação do seu primeiro comandante, <NAME> com o posto que lhe foi dado.
 Emblema do SAC

Em 19 outubro de 1948, LeMay assumiu o comando do SAC (ocupando o posto até Junho de 1957), realizando profundas mudanças, tornando o SAC a força militar mais poderosa do mundo em pouco tempo.

Para cumprir a missão original do SAC, LeMay iniciou várias operações visando maximizar a abrangência e tempo de reação a qualquer ataque que os EUA pudessem sofrer. Dessas operações, uma das mais importantes é a Chrome Dome.

A Operação Chrome Dome consistiu em manter no ar, de forma constante, de bombardeios B-52 com bombas atômicas. Ou seja, mesmo que todas as bases americanas sofressem um ataque massivo, uma força significante sempre estaria no ar, em posição de ataque.

Abaixo temos os esquemas de voo:

Para manter essa força constante no ar, sobre os EUA e sobre países aliados na Europa, os B-52 faziam vários reabastecimentos no ar.

Em 17 de janeiro, um B-52 já havia atingido o ponto mais distante da missa, e estava retornando para a sua base em na Carolina do Norte - EUA. A sua missão previa um terceiro reabastecimento sobre o Mar Mediterrâneo, com um KC-135 vindo da base Moron AFB, próxima a Sevilha - Espanha.
Indícios apontam que, durante o reabastecimento, o B-52 não conseguiu parear a sua velocidade com a do avião tanque. Desta forma, o braço de reabastecimento colidiu com o bombardeio, causando a sua queda sobre a Espanha, próximo a uma vila de pescadores chamada Palomares.

O KC-135 explodiu no ar, matando toda a sua tripulação. 4 homens da tripulação do B-52 conseguiram usar seus para-quedas e sobreviveram.

Termino a introdução desta postagem com o discurso Sinews of Peace, proferido por <NAME> em 5 de março de 1946, no Westminster College, Fulton, Missouri.

Próxima postagem: Broken Arrow - O acidente de Palomares - A aeronave

President McCluer, ladies and gentlemen, and last, but certainly not least, the President of the United States of America:

I am very glad indeed to come to Westminster College this afternoon, and I am complimented that you should give me a degree from an institution whose reputation has been so solidly established. The name "Westminster" somehow or other seems familiar to me. I feel as if I have heard of it before. Indeed now that I come to think of it, it was at Westminster that I received a very large part of my education in politics, dialectic, rhetoric, and one or two other things. In fact we have both been educated at the same, or similar, or, at any rate, kindred establishments.

It is also an honor, ladies and gentlemen, perhaps almost unique, for a private visitor to be introduced to an academic audience by the President of the United States. Amid his heavy burdens, duties, and responsibilities--unsought but not recoiled from--the President has traveled a thousand miles to dignify and magnify our meeting here to-day and to give me an opportunity of addressing this kindred nation, as well as my own countrymen across the ocean, and perhaps some other countries too. The President has told you that it is his wish, as I am sure it is yours, that I should have full liberty to give my true and faithful counsel in these anxious and baffling times. I shall certainly avail myself of this freedom, and feel the more right to do so because any private ambitions I may have cherished in my younger days have been satisfied beyond my wildest dreams. Let me however make it clear that I have no official mission or status of any kind, and that I speak only for myself. There is nothing here but what you see.

I can therefore allow my mind, with the experience of a lifetime, to play over the problems which beset us on the morrow of our absolute victory in arms, and to try to make sure with what strength I have that what has gained with so much sacrifice and suffering shall be preserved for the future glory and safety of mankind.

Ladies and gentlemen, the United States stands at this time at the pinnacle of world power. It is a solemn moment for the American Democracy. For with primacy in power is also joined an awe-inspiring accountability to the future. If you look around you, you must feel not only the sense of duty done but also you must feel anxiety lest you fall below the level of achievement. Opportunity is here and now, clear and shining for both our countries. To reject it or ignore it or fritter it away will bring upon us all the long reproaches of the after-time. It is necessary that the constancy of mind, persistency of purpose, and the grand simplicity of decision shall rule and guide the conduct of the English-speaking peoples in peace as they did in war. We must, and I believe we shall, prove ourselves equal to this severe requirement.

President McCluer, when American military men approach some serious situation they are wont to write at the head of their directive the words "over-all strategic concept". There is wisdom in this, as it leads to clarity of thought. What then is the over-all strategic concept which we should inscribe to-day? It is nothing less than the safety and welfare, the freedom and progress, of all the homes and families of all the men and women in all the lands. And here I speak particularly of the myriad cottage or apartment homes where the wage-earner strives amid the accidents and difficulties of life to guard his wife and children from privation and bring the family up the fear of the Lord, or upon ethical conceptions which often play their potent part.

To give security to these countless homes, they must be shielded form two gaunt marauders, war and tyranny. We al know the frightful disturbance in which the ordinary family is plunged when the curse of war swoops down upon the bread-winner and those for whom he works and contrives. The awful ruin of Europe, with all its vanished glories, and of large parts of Asia glares us in the eyes. When the designs of wicked men or the aggressive urge of mighty States dissolve over large areas the frame of civilized society, humble folk are confronted with difficulties with which they cannot cope. For them is all distorted, all is broken, all is even ground to pulp.

When I stand here this quiet afternoon I shudder to visualize what is actually happening to millions now and what is going to happen in this period when famine stalks the earth. None can compute what has been called "the unestimated sum of human pain". Our supreme task and duty is to guard the homes of the common people from the horrors and miseries of another war. We are all agreed on that.

Our American military colleagues, after having proclaimed their "over-all strategic concept" and computed available resources, always proceed to the next step -- namely, the method. Here again there is widespread agreement. A world organization has already been erected for the prime purpose of preventing war. UNO, the successor of the League of Nations, with the decisive addition of the United States and all that that means, is already at work. We must make sure that its work is fruitful, that it is a reality and not a sham, that it is a force for action, and not merely a frothing of words, that it is a true temple of peace in which the shields of many nations can some day be hung up, and not merely a cockpit in a Tower of Babel. Before we cast away the solid assurances of national armaments for self-preservation we must be certain that our temple is built, not upon shifting sands or quagmires, but upon a rock. Anyone can see with his eyes open that our path will be difficult and also long, but if we persevere together as we did in the two world wars -- though not, alas, in the interval between them -- I cannot doubt that we shall achieve our common purpose in the end.

I have, however, a definite and practical proposal to make for action. Courts and magistrates may be set up but they cannot function without sheriffs and constables. The United Nations Organization must immediately begin to be equipped with an international armed force. In such a matter we can only go step by step, but we must begin now. I propose that each of the Powers and States should be invited to dedicate a certain number of air squadrons to the service of the world organization. These squadrons would be trained and prepared in their own countries, but would move around in rotation from one country to another. They would wear the uniforms of their own countries but with different badges. They would not be required to act against their own nation, but in other respects they would be directed by the world organization. This might be started on a modest scale and it would grow as confidence grew. I wished to see this done after the first world war, and I devoutly trust that it may be done forthwith.

It would nevertheless, ladies and gentlemen, be wrong and imprudent to entrust the secret knowledge or experience of the atomic bomb, which the United States, great Britain, and Canada now share, to the world organization, while still in its infancy. It would be criminal madness to cast it adrift in this still agitated and un-united world. No one country has slept less well in their beds because this knowledge and the method and the raw materials to apply it, are present largely retained in American hands. I do not believe we should all have slept so soundly had the positions been reversed and some Communist or neo-Facist State monopolized for the time being these dread agencies. The fear of them alone might easily have been used to enforce totalitarian systems upon the free democratic world, with consequences appalling to human imagination. God has willed that this shall not be and we have at least a breathing space to set our world house in order before this peril has to be encountered: and even then, if no effort is spared, we should still possess so formidable a superiority as to impose effective deterrents upon its employment, or threat of employment, by others. Ultimately, when the essential brotherhood of man is truly embodied and expressed in a world organization with all the necessary practical safeguards to make it effective, these powers would naturally be confided to that world organizations.

Now I come to the second of the two marauders, to the second danger which threatens the cottage homes, and the ordinary people -- namely, tyranny. We cannot be blind to the fact that the liberties enjoyed by individual citizens throughout the United States and throughout the British Empire are not valid in a considerable number of countries, some of which are very powerful. In these States control is enforced upon the common people by various kinds of all-embracing police governments to a degree which is overwhelming and contrary to every principle of democracy. The power of the State is exercised without restraint, either by dictators or by compact oligarchies operating through a privileged party and a political police. It is not our duty at this time when difficulties are so numerous to interfere forcibly in the internal affairs of countries which we have not conquered in war. but we must never cease to proclaim in fearless tones the great principles of freedom and the rights of man which are the joint inheritance of the English-speaking world and which through Magna Carta, the Bill of rights, the Habeas Corpus, trial by jury, and the English common law find their most famous expression in the American Declaration of Independence.

All this means that the people of any country have the right, and should have the power by constitutional action, by free unfettered elections, with secret ballot, to choose or change the character or form of government under which they dwell; that freedom of speech and thought should reign; that courts of justice, independent of the executive, unbiased by any party, should administer laws which have received the broad assent of large majorities or are consecrated by time and custom. Here are the title deeds of freedom which should lie in every cottage home. Here is the message of the British and American peoples to mankind. Let us preach what we practice -- let us practice what we preach.

though I have now stated the two great dangers which menace the home of the people, War and Tyranny, I have not yet spoken of poverty and privation which are in many cases the prevailing anxiety. But if the dangers of war and tyranny are removed, there is no doubt that science and cooperation can bring in the next few years, certainly in the next few decades, to the world, newly taught in the sharpening school of war, an expansion of material well-being beyond anything that has yet occurred in human experience.

Now, at this sad and breathless moment, we are plunged in the hunger and distress which are the aftermath of our stupendous struggle; but this will pass and may pass quickly, and there is no reason except human folly or sub-human crime which should deny to all the nations the inauguration and enjoyment of an age of plenty. I have often used words which I learn fifty years ago from a great Irish-American orator, a friend of mine, Mr. <NAME>, "There is enough for all. The earth is a generous mother; she will provide in plentiful abundance food for all her children if they will but cultivate her soil in justice and peace." So far I feel that we are in full agreement.

Now, while still pursing the method -- the method of realizing our over-all strategic concept, I come to the crux of what I have traveled here to say. Neither the sure prevention of war, nor the continuous rise of world organization will be gained without what I have called the fraternal association of the English-speaking peoples. This means a special relationship between the British Commonwealth and Empire and the United States of America. Ladies and gentlemen, this is no time for generality, and I will venture to the precise. Fraternal association requires not only the growing friendship and mutual understanding between our two vast but kindred systems of society, but the continuance of the intimate relations between our military advisers, leading to common study of potential dangers, the similarity of weapons and manuals of instructions, and to the interchange of officers and cadets at technical colleges. It should carry with it the continuance of the present facilities for mutual security by the joint use of all Naval and Air Force bases in the possession of either country all over the world. This would perhaps double the mobility of the American Navy and Air Force. It would greatly expand that of the British Empire forces and it might well lead, if and as the world calms down, to important financial savings. Already we use together a large number of islands; more may well be entrusted to our joint care in the near future.

the United States has already a Permanent Defense Agreement with the Dominion of Canada, which is so devotedly attached to the British Commonwealth and the Empire. This Agreement is more effective than many of those which have been made under formal alliances. This principle should be extended to all the British Commonwealths with full reciprocity. Thus, whatever happens, and thus only, shall we be secure ourselves and able to works together for the high and simple causes that are dear to us and bode no ill to any. Eventually there may come -- I feel eventually there will come -- the principle of common citizenship, but that we may be content to leave to destiny, whose outstretched arm many of us can already clearly see.

There is however an important question we must ask ourselves. Would a special relationship between the United States and the British Commonwealth be inconsistent with our over-riding loyalties to the World Organization? I reply that, on the contrary, it is probably the only means by which that organization will achieve its full stature and strength. There are already the special United States relations with Canada that I have just mentioned, and there are the relations between the United States and the South American Republics. We British have also our twenty years Treaty of Collaboration and Mutual Assistance with Soviet Russia. I agree with Mr. Bevin, the Foreign Secretary of Great Britain, that it might well be a fifty years treaty so far as we are concerned. We aim at nothing but mutual assistance and collaboration with Russia. The British have an alliance with Portugal unbroken since the year 1384, and which produced fruitful results at a critical moment in the recent war. None of these clash with the general interest of a world agreement, or a world organization; on the contrary, they help it. "In my father's house are many mansions." Special associations between members of the United Nations which have no aggressive point against any other country, which harbor no design incompatible with the Charter of the United Nations, far from being harmful, are beneficial and, as I believe, indispensable.

I spoke earlier, ladies and gentlemen, of the Temple of Peace. Workmen from all countries must build that temple. If two of the workmen know each other particularly well and are old friends, if their families are intermingled, if they have "faith in each other's purpose, hope in each other's future and charity towards each other's shortcomings" -- to quote some good words I read here the other day -- why cannot they work together at the common task as friends and partners? Why can they not share their tools and thus increase each other's working powers? Indeed they must do so or else the temple may not be built, or, being built, it may collapse, and we should all be proved again unteachable and have to go and try to learn again for a third time in a school of war incomparably more rigorous than that from which we have just been released. The dark ages may return, the Stone Age may return on the gleaming wings of science, and what might now shower immeasurable material blessings upon mankind, may even bring about its total destruction. Beware, I say; time may be short. Do not let us take the course of allowing events to drift along until it is too late. If there is to be a fraternal association of the kind of I have described, with all the strength and security which both our countries can derive from it, let us make sure that that great fact is known to the world, and that it plays its part in steadying and stabilizing the foundations of peace. There is the path of wisdom. Prevention is better than the cure.

A shadow has fallen upon the scenes so lately light by the Allied victory. Nobody knows what Soviet Russia and its Communist international organization intends to do in the immediate future, or what are the limits, if any, to their expansive and proselytizing tendencies. I have a strong admiration and regard for the valiant Russian people and for my wartime comrade, <NAME>. There is deep sympathy and goodwill in Britain -- and I doubt not here also -- towards the peoples of all the Russias and a resolve to persevere through many differences and rebuffs in establishing lasting friendships. We understand the Russian need to be secure on her western frontiers by the removal of all possibility of German aggression. We welcome Russia to her rightful place among the leading nations of the world. We welcome her flag upon the seas. Above all, we welcome, or should welcome, constant, frequent and growing contacts between the Russian people and our own people on both sides of the Atlantic. It is my duty however, for I am sure you would wish me to state the facts as I see them to you. It is my duty to place before you certain facts about the present position in Europe.

From Stettin in the Baltic to Trieste in the Adriatic an iron curtain has descended across the Continent. Behind that line lie all the capitals of the ancient states of Central and Eastern Europe. Warsaw, Berlin, Prague, Vienna, Budapest, Belgrade, Bucharest and Sofia, all these famous cities and the populations around them lie in what I must call the Soviet sphere, and all are subject in one form or another, not only to Soviet influence but to a very high and, in some cases, increasing measure of control from Moscow. Athens alone -- Greece with its immortal glories -- is free to decide its future at an election under British, American and French observation. The Russian-dominated Polish Government has been encouraged to make enormous and wrongful inroads upon Germany, and mass expulsions of millions of Germans on a scale grievous and undreamed-of are now taking place. The Communist parties, which were very small in all these Eastern States of Europe, have been raised to pre-eminence and power far beyond their numbers and are seeking everywhere to obtain totalitarian control. Police governments are prevailing in nearly every case, and so far, except in Czechoslovakia, there is no true democracy.

Turkey and Persia are both profoundly alarmed and disturbed at the claims which are being made upon them and at the pressure being exerted by the Moscow Government. An attempt is being made by the Russians in Berlin to build up a quasi-Communist party in their zone of occupied Germany by showing special favors to groups of left-wing German leaders. At the end of the fighting last June, the American and British Armies withdrew westward, in accordance with an earlier agreement, to a depth at some points of 150 miles upon a front of nearly four hundred miles, in order to allow our Russian allies to occupy this vast expanse of territory which the Western Democracies had conquered.

If no the Soviet Government tries, by separate action , to build up a pro-Communist Germany in their areas, this will cause new serious difficulties in the American and British zones, and will give the defeated Germans the power of putting themselves up to auction between the Soviets and the Western Democracies. Whatever conclusions may be drawn from these facts -- and facts they are -- this is certainly not the Liberated Europe we fought to build up. Nor is it one which contains the essentials of permanent peace.

The safety of the world, ladies and gentlemen, requires a new unity in Europe, from which no nation should be permanently outcast. It is from the quarrels of the strong parent races in Europe that the world wars we have witnessed, or which occurred in former times, have sprung. Twice in our own lifetime we have seen the United States, against their wished and their traditions, against arguments, the force of which it is impossible not to comprehend, twice we have seen them drawn by irresistible forces, into these wars in time to secure the victory of the good cause, but only after frightful slaughter and devastation have occurred. Twice the United State has had to send several millions of its young men across the Atlantic to find the war; but now war can find any nation, wherever it may dwell between dusk and dawn. Surely we should work with conscious purpose for a grand pacification of Europe, within the structure of the United Nations and in accordance with our Charter. That I feel opens a course of policy of very great importance.

In front of the iron curtain which lies across Europe are other causes for anxiety. In Italy the Communist Party is seriously hampered by having to support the Communist-trained <NAME>'s claims to former Italian territory at the head of the Adriatic. Nevertheless the future of Italy hangs in the balance. Again one cannot imagine a regenerated Europe without a strong France. All my public life I never last faith in her destiny, even in the darkest hours. I will not lose faith now. However, in a great number of countries, far from the Russian frontiers and throughout the world, Communist fifth columns are established and work in complete unity and absolute obedience to the directions they receive from the Communist center. Except in the British Commonwealth and in the United States where Communism is in its infancy, the Communist parties or fifth columns constitute a growing challenge and peril to Christian civilization. These are somber facts for anyone to have recite on the morrow a victory gained by so much splendid comradeship in arms and in the cause of freedom and democracy; but we should be most unwise not to face them squarely while time remains.

The outlook is also anxious in the Far East and especially in Manchuria. The Agreement which was made at Yalta, to which I was a party, was extremely favorable to Soviet Russia, but it was made at a time when no one could say that the German war might no extend all through the summer and autumn of 1945 and when the Japanese war was expected by the best judges to last for a further 18 months from the end of the German war. In this country you all so well-informed about the Far East, and such devoted friends of China, that I do not need to expatiate on the situation there.

I have, however, felt bound to portray the shadow which, alike in the west and in the east, falls upon the world. I was a minister at the time of the Versailles treaty and a close friend of Mr. Lloyd-George, who was the head of the British delegation at Versailles. I did not myself agree with many things that were done, but I have a very strong impression in my mind of that situation, and I find it painful to contrast it with that which prevails now. In those days there were high hopes and unbounded confidence that the wars were over and that the League of Nations would become all-powerful. I do not see or feel that same confidence or event he same hopes in the haggard world at the present time.

On the other hand, ladies and gentlemen, I repulse the idea that a new war is inevitable; still more that it is imminent. It is because I am sure that our fortunes are still in our own hands and that we hold the power to save the future, that I feel the duty to speak out now that I have the occasion and the opportunity to do so. I do not believe that Soviet Russia desires war. What they desire is the fruits of war and the indefinite expansion of their power and doctrines. But what we have to consider here today while time remains, is the permanent prevention of war and the establishment of conditions of freedom and democracy as rapidly as possible in all countries. Our difficulties and dangers will not be removed by closing our eyes to them. They will not be removed by mere waiting to see what happens; nor will they be removed by a policy of appeasement. What is needed is a settlement, and the longer this is delayed, the more difficult it will be and the greater our dangers will become.

From what I have seen of our Russian friends and Allies during the war, I am convinced that there is nothing for which they have less respect than for weakness, especially military weakness. For that reason the old doctrine of a balance of power is unsound. We cannot afford, if we can help it, to work on narrow margins, offering temptations to a trial of strength. If the Western Democracies stand together in strict adherence to the principles will be immense and no one is likely to molest them. If however they become divided of falter in their duty and if these all-important years are allowed to slip away then indeed catastrophe may overwhelm us all.

Last time I saw it all coming and I cried aloud to my own fellow-countrymen and to the world, but no one paid any attention. Up till the year 1933 or even 1935, Germany might have been saved from the awful fate which has overtaken here and we might all have been spared the miseries Hitler let loose upon mankind. there never was a war in history easier to prevent by timely action than the one which has just desolated such great areas of the globe. It could have been prevented in my belief without the firing of a single shot, and Germany might be powerful, prosperous and honored today; but no one would listen and one by one we were all sucked into the awful whirlpool. We surely, ladies and gentlemen, I put it to you, surely, we must not let it happen again. This can only be achieved by reaching now, in 1946, by reaching a good understanding on all points with Russia under the general authority of the United Nations Organization and by the maintenance of that good understanding through many peaceful years, by the whole strength of the English-speaking world and all its connections. There is the solution which I respectfully offer to you in this Address to which I have given the title, "The Sinews of Peace".

Let no man underrate the abiding power of the British Empire and Commonwealth. Because you see the 46 millions in our island harassed about their food supply, of which they only grow one half, even in war-time, or because we have difficulty in restarting our industries and export trade after six years of passionate war effort, do not suppose we shall not come through these dark years of privation as we have come through the glorious years of agony. Do not suppose that half a century from now you will not see 70 or 80 millions of Britons spread about the world united in defense of our traditions, and our way of life, and of the world causes which you and we espouse. If the population of the English-speaking Commonwealths be added to that of the United States with all that such co-operation implies in the air, on the sea, all over the globe and in science and in industry, and in moral force, there will be no quivering, precarious balance of power to offer its temptation to ambition or adventure. On the contrary there will be an overwhelming assurance of security. If we adhere faithfully to the Charter of the United Nations and walk forward in sedate and sober strength seeking no one's land or treasure, seeking to lay no arbitrary control upon the thoughts of men; if all British moral and material forces and convictions are joined with your own in fraternal association, the highroads of the future will be clear, not only for our time, but for a century to come.

## quarta-feira, 23 de novembro de 2011

### Mapas Omaha Beach

Mapas pré-invasão da praia de Omaha. Clique nas imagens para aumentar.

No verso dos mapas, temos tabelas de nascer e por do sol e gradientes das praias. Me pergunto como foram esquecer dessas informações na invasão da Baía dos Porcos...

 Omaha Beach - East (Colleville-sur-Mer), 21 de abril de 1944 (frente)

 Omaha Beach - East (Colleville-sur-Mer), 21 de abril de 1944 (verso)

 Omaha Beach - West (Vierville-sur-Mer), 21 de abril de 1944 (frente)

 Omaha Beach - West (Vierville-sur-Mer), 21 de abril de 1944 (verso)

## segunda-feira, 21 de novembro de 2011

### História Ilustrada da Segunda Guerra Mundial

Com certeza os leitores desse blog conhecem os livros da coleção História Ilustrada da Segunda Guerra Mundial.

Esses pequenos livros, apesar da encadernação de qualidade duvidosa, apresentam boas figuras e fotos acompanhados de bons textos e traduções razoáveis, cobrindo vários aspectos da Segunda Guerra Mundial, com as seguintes séries:

• Batalhas;
• Tropas;
• Líderes;
• Armas;
• Política em ação;
• Conflito humano;
• Campanhas.
A pouco tempo descobri que a Editora Renes ainda existe (!), e que podemos comprar a coleção completa. A quem interessar, segue o link: http://www.editorarenes.com.br/

Eu ainda prefiro ir montando a coleção comprando nos sebos... aceito doações e pago o frete :-)

## segunda-feira, 14 de novembro de 2011

### O problema da produção de tanques alemães

A determinação da força militar oponente é chave para a vitória, e os aliados muito dependiam dessas informações para se preparar e enfrentar as colunas blindadas alemãs, tendo a real noção do quanto as baixas infligidas no inimigo o afetava.

Assim, a estimação da produção de armamentos, incluindo blindados, era um grande objetivo dos serviços de inteligência.

Através de espionagem e outros métodos convencionais, os aliados chegaram ao número de 1.400 tanques Panther produzidor por mês, entre Junho de 1940 e Setembro de 1942. Contudo, esta estimação não se confirmava em tanque, pois, com um número tão alto, a reposição dos veículos abatidos e até mesmo a formação de novos regimentos deveria ser maior e mais rápida do que o observado. Assim, está predição começou a ficar desacreditada, e os serviços de inteligência começaram a investir em outros métodos de estimação.

Observando cuidadosamente os veículos abatidos, notou-se que todos eles continham um número de série único inscrito nas caixas de marcha (e outros em chassis e outras pastes). Esta foi a chave para a estimação quase que sem erro da produção de blindados alemães.

Atualmente, várias análises estatísticas podem ser empregadas para a estimação do número de veículos, incluindo abordagens bayesianas. A abordagem mais comum é a estimação pontual através do estimador de variância mínima não enviesada. Apesar do nome complicado, a sua fórmula é simples:

Onde m é o maior valor serial encontrado em uma amostra de veículos, e k é o tamanho desta amostra. Naturalmente, quanto maior a amostra, mais exata é a estimação.

Um exemplo: suponha que a produção real em um mês seja de 20 veículos, e que destes 20, foram abatidos os seriais 2, 4, 8, 9, 10, 13 e 19. Então temos um m=19 e k=7. Aplicando os valores na fórmula, temos um N estimado de 20,71; bem próximo a produção real.

Aplicando-se este método, chegou-se a seguinte comparação:

 Mês Estimação estatística Estimação da intelilgência convencional Registros alemães Junho 1940 169 1000 122 Junho 1941 244 1550 271 Agosto 1942 327 1550 342

Observando a estimação estatística e os registros de produção alemães, encontrados após a invasão, vemos que o erro médio da estimação é de apenas 2 veículos, contra o erro médio de 1120 em comparação com os métodos convencionais de inteligência.

format: plain


text:
## Comparing objects in Php

In this tutorial we are going to be looking at how to compare objects in PHP, first using the comparison operator (==) and then using identity operator (===).

As we shall see, each of the two operators behave differently based whether:

• The objects are the same instance or different instances of a class
• The object properties and their values are the same or not.

### Object comparison using the equality operator ==

The "equal to" operator (==) compares if objects are holding the same property values and are instances of the same class. For example:

#### Example 1

<?php

class Spaceship {
public $velocity = 23; public$name = "<NAME>";
public $enemy = false; }$command_ship = new Spaceship;
$service_ship = new Spaceship;$result = ($command_ship ==$service_ship);

var_dump($result); //> bool(true) ?>  In the example above, the comparison returned true because $command_ship and $service_ship are instances of the same class and their properties hold the same values. #### Example 2 <?php class Spaceship { public$velocity = 23;
public $name = "<NAME>"; public$enemy = false;

}

$command_ship = new Spaceship;$command_ship = "HMS Sytech Zimbabwe";

$service_ship = new Spaceship;$result = ($command_ship ==$service_ship);

var_dump($result); //> bool(false) ?>  This time, the comparison returned false because, even though $command_ship and $service_ship are instances of the same class, we changed the name property of object $command_ship and their properties no longer hold the same values. Changing the value of an instance variable in one object does not reflect in the other.

### Object comparison using the strict equality operator ===

The "strictly equal to" operator (===) returns true only if the variables refer to the same instance of the same class. For example:

#### Example 1

<?php

class Spaceship {
public $velocity = 23; public$name = "<NAME>";
public $enemy = false; }$command_ship = new Spaceship;
$service_ship = new Spaceship;$result = ($command_ship ===$service_ship);

var_dump($result); //> bool(false) ?>  The comparison returned false because the objects are not the same instance of the same class. #### Example 2 <?php class Spaceship { public$velocity = 23;
public $name = "HMS <NAME>"; public$enemy = false;

}

$command_ship = new Spaceship;$service_ship = $command_ship;$result = ($command_ship ===$service_ship);

var_dump($result); //> bool(true) ?>  The comparison returned true because the objects are the same instance of the same class, since we literally assigned the reference of $command_ship to \$service_ship.


text:
# skrf.calibration.calibration.UnknownThru¶

class skrf.calibration.calibration.UnknownThru(measured, ideals, *args, **kwargs)[source]

Two-Port Self-Calibration allowing the thru standard to be unknown.

This algorithm was originally developed in [1], and is based on the 8-term error model (EightTerm). It allows the thru to be unknown, other than it must be reciprocal. This is useful when when a well-known thru is not realizable.

References

 [1] Ferrero and <NAME>, “Two-port network analyzer calibration using an unknown thru,” IEEE Microwave and Guided Wave Letters, vol. 2, no. 12, pp. 505-507, 1992.

Attributes

 T_matrices Intermediate matrices used for embedding and de-embedding. biased_error Estimate of biased error for overdetermined calibration with multiple connections of each standard caled_ntwk_sets Returns a NetworkSet for each caled_ntwk, grouped by their names caled_ntwks List of the corrected calibration standards coefs Dictionary or error coefficients in form of numpy arrays coefs_12term Dictionary of error coefficients for 12-term Model coefs_12term_ntwks Dictionary or error coefficients in form of Network objects coefs_3term Dictionary of error coefficients for One-port Error model coefs_3term_ntwks Dictionary of error coefficients in form of Network objects coefs_8term Dictionary of error coefficients for 8-term (Error-box) Model coefs_8term_ntwks Dictionary of error coefficients in form of Network objects coefs_ntwks Dictionary of error coefficients in form of Network objects error_ntwk The calculated error Network or Network[s] family frequency Frequency object of the calibration measured_unisolated measured_unterminated normalized_directivity the directivity normalized to the reflection tracking nstandards number of ideal/measurement pairs in calibration output_from_run Returns any output from the run(). residual_ntwk_sets Returns a NetworkSet for each residual_ntwk, grouped by their names residual_ntwks Dictionary of residual Networks total_error Estimate of total error for overdetermined calibration with multiple connections of each standard.This is the combined effects of both biased and un-biased errors unbiased_error Estimate of unbiased error for overdetermined calibration with multiple connections of each standard verify_12term verify_12term_ntwk

Methods

 __init__ Initializer apply_cal Apply correction to a Network apply_cal_to_all_in_dir Apply correction to all touchstone files in a given directory. apply_cal_to_list Apply correction to list of dict of Networks. apply_cal_to_network_set Apply correction to a NetworkSet. embed from_coefs Creates a calibration from its error coefficients from_coefs_ntwks Creates a calibration from its error coefficients plot_caled_ntwks Plots corrected calibration standards plot_errors Plots biased, unbiased and total error in dB scaled plot_residuals Plot residual networks. pop Remove and return tuple of (ideal, measured) at index. remove_and_cal Remove a cal standard and correct it, returning correct and ideal renormalize Renormalizes the calibration error boxes to a new reference impedance. run Runs the calibration algorithm. terminate Terminate a network with switch terms unterminate Unterminates switch terms from a raw measurement. update_coefs update currect dict of error coefficients write Write the Calibration to disk using write()


text:
## Filters

Sort by :
Clear All
Q

4.4  The decomposition of dimethyl ether leads to the formation of $CH_{4}$, $H_{2}$ and $CO$  and the reaction rate is given by $Rate=k\left [ CH_{3}OCH_{3} \right ]^{3/2}$
The rate of reaction is followed by increase in pressure in a closed vessel, so the rate can also be expressed in terms of the partial pressure of dimethyl ether, i.e.,
$Rate=k\left [ P_{CH_{3}OCH_{3} \right ]^{3/2}$
If the pressure is measured in bar and time in minutes, then what are the units of rate and rate constants?

Given that  So, the unit of rate is bar/min.() And thus the unit of k = unit of rate
Exams
Articles
Questions


text:
Resources for Structural Engineers and Engineering Students

Question 1

(a) $M_{AB}=209\mathrm{\,kNm}$, $M_{BC}=143\mathrm{\,kNm}$

(b) $M_{AB}=64.6\mathrm{\,kNm}$, $M_{BC}=45.7\mathrm{\,kNm}$

(c) $M_{AB}=-43.5\mathrm{\,kNm}$, $M_{BC}=143\mathrm{\,kNm}$

(d) $M_{BA}=-113\mathrm{\,kNm}$, $M_{CB}=-108\mathrm{\,kNm}$

Question 2

$M_{AB}=250\mathrm{\,kNm}$, $M_{BC}=-157\mathrm{\,kNm}$

Question 3

$M_{AB}=303\mathrm{\,kNm}$, $M_{CB}=-117\mathrm{\,kNm}$

Question 4

(a) $M_{AB}=36.0\mathrm{\,kNm}$, $M_{BC}=152\mathrm{\,kNm}$

(b) $M_{AB}=176\mathrm{\,kNm}$, $M_{BD}=136\mathrm{\,kNm}$

(c) $M_{BA}=-119\mathrm{\,kNm}$, $M_{BD}=-178\mathrm{\,kNm}$

Question 5

$M_{AB}=19.3\mathrm{\,kNm}$, $M_{BC}=185\mathrm{\,kNm}$

Question 6

$M_{BA}=-300\mathrm{\,kNm}$, $M_{BD}=-50.6\mathrm{\,kNm}$

Question 7

$M_{AB}=494\mathrm{\,kNm}$, $M_{BD}=533\mathrm{\,kNm}$


text:
# Random numbers in C++ and Mathematica gives wrong results? [closed]

I have the following strange phenomenon which puzzles me!:

I have a piecewise constant probability density given as

using RandomGenType = std::mt19937_64;
RandomGenType gen(51651651651);

using PREC = long double;
std::array<PREC,5> intervals {0.59, 0.7, 0.85, 1, 1.18};
std::array<PREC,4> weights {1.36814, 1.99139, 0.29116, 0.039562};

// integral over the pdf to normalize:
PREC normalization =0;
for(unsigned int i=0;i<4;i++){
normalization += weights[i]*(intervals[i+1]-intervals[i]);
}
std::cout << std::setprecision(30) << "Normalization: " << normalization << std::endl;
// normalize all weights (such that the integral gives 1)!
for(auto & w : weights){
w /= normalization;
}

std::piecewise_constant_distribution<PREC>
distribution (intervals.begin(),intervals.end(),weights.begin());

When I draw n random numbers (radius of sphere in millimeters) from this distribution and compute the mass of the sphere and sum them up like:

unsigned int n = 1000000;
double density = 2400;
double mass = 0;

for(int i=0;i<n;i++){
auto d = 2* distribution(gen) * 1e-3;
mass += d*d*d/3.0*M_PI_2*density;
}

I get mass = 4.3283 kg (see LIVE and the c++ post)

Doing the EXACT identical thing in Mathematica like:

Gives the assumably correct value of 4.5287 kg.

Which is not the same, also with different seeds , C++ and Mathematica never match! ? Is that numeric inaccuracy, which I doubt it is...? Question : What the hack is wrong with the sampling in C++?

Simple Mathematica Code:

pdf[r_] = 2*Piecewise[{{0, r < 0.59}, {1.36814, 0.59 <= r <= 0.7},
{1.99139, Inequality[0.7, Less, r, LessEqual, 0.85]},
{0.29116, Inequality[0.85, Less, r, LessEqual, 1]},
{0.039562, Inequality[1, Less, r, LessEqual, 1.18]},
{0, r > 1.18}}];

pdfr[r_] = pdf[r] / Integrate[pdf[r], {r, 0, 3}];(*normalize*)

Plot[pdf[r], {r, 0.4, 1.3}, Filling -> Axis]

PDFr = ProbabilityDistribution[pdfr[r], {r, 0, 1.18}];
(*if you put 1.18=2 then we dont get 4.52??*)

SeedRandom[100, Method -> "MersenneTwister"]
dataR = RandomVariate[PDFr, 1000000, WorkingPrecision -> MachinePrecision];
Fold[#1 + (2*#2*10^-3)^3  Pi/6 2400 &, 0, dataR]

(*Analytical Solution*)

PDFr = ProbabilityDistribution[pdfr[r], {r, 0, 3}];
1000000 Integrate[ 2400 (2 InverseCDF[PDFr, p] 10^-3)^3 Pi/6, {p, 0, 1}]

## closed as off-topic by Mr.Wizard♦Mar 10 '15 at 2:49

• The question does not concern the technical computing software Mathematica by Wolfram Research. Please see the help center to find out about the topics that can be asked here.
If this question can be reworded to fit the rules in the help center, please edit the question.

• the pdf you supply to ProbabilityDistribution must be a proper probability density function in the sense that it integrates to unity over the interval. ( yours integrates to ~1/2 ) – george2079 Mar 4 '15 at 19:35
• ups jeah, sorry, should be 2 times this, (edit) – Gabriel Mar 4 '15 at 19:38
• Ok, Thanks. I see that with n=2000000 your C-code gives 8.65219 and Mathematica 9.0509. (The difference increases with n). I suppose this should not be correct, isn't it? – Dargor Mar 4 '15 at 19:58
• Isn't this more of a C++ question than a Mathematica one? – <NAME> Mar 4 '15 at 21:29
• The c++ question is here: stackoverflow.com/questions/28862895/… – Gabriel Mar 4 '15 at 23:59

a bit of an extended comment,

Note there is no need for a delayed defintion of your pdf:

 pdf[r_] =
Simplify[2 (Piecewise[{{0, r <= 0.59}, {1.36814,
Inequality[0.59, Less, r, LessEqual, 0.7]}, {0, r > 0.7}},
Indeterminate] +
Piecewise[{{0, r <= 0.7}, {1.99139,
Inequality[0.7, Less, r, LessEqual, 0.85]}, {0, r > 0.85}},
Indeterminate] +
Piecewise[{{0., r <= 0.85}, {0.29116,
Inequality[0.85, Less, r, LessEqual, 1]}, {0., r > 1}},
Indeterminate] +
Piecewise[{{0, r <= 1}, {0.039562,
Inequality[1, Less, r, LessEqual, 1.18]}, {0, r > 1.18}},
Indeterminate])];

This integrates to nearly 1, but lets normalize it so its exact: (the factor is ~0.999998 )

 pdf[r_] =  pdf[r]/Integrate[ pdf[r], {r, .59, 1.18}] // Simplify

Now you can get your result analytically: (this fails if you don't do the normalization)

 PDFr = ProbabilityDistribution[pdf[r], {r, 0.59, 1.18}];
1000000 Integrate[ 2400 ( 2 InverseCDF[PDFr, p] 10^-3)^3 Pi/6  , {p, 0, 1}]

4.52594

This is true because: $mass = (2r)^3 \frac{\pi}{6}\rho, \quad r \backsim F_R :\textnormal{(CDF radius)} \\ x = F_R^{-1}(u) \textnormal{ with } u \backsim Uniform(0,1) \Rightarrow x \backsim F_R \\ \Rightarrow mass = (2 F_R^{-1})^3 \frac{\pi}{6}\rho = g(u) \quad \Rightarrow E[mass] = \int_{0}^1 g(u) f_u(u) du = \int_{0}^1 g(u) du$

This seems fairly convincing that your mathematica monte carlo is correct and the trouble lies in the c version.

• Jeap, I tested that too! Thanks for the comment! it seems that the c++ is buggy! – Gabriel Mar 4 '15 at 20:32
• Sorry, I was mistaken, I did not test that, can you quickly give me a hint, why you integrate the inverse cdf? The term Integrate[ 2400 ( 2 InverseCDF[PDFr, p] 10^-3)^3 Pi/6 , {p, 0, 1}]is the expected mass of one sphere I assume, but why :-)? – Gabriel Mar 4 '15 at 23:15


text:
Matrix question

1. Feb 5, 2006

Mathman23

Hi

I got a question regarding a matrix expression:

Let $$X \in Mat_{n,n} (\mathbf{F})$$. Then I'm suppose to show AX = XA for all $$A \in Mat_{n,n} \mathbf{(F)}$$ if and only if $$s \in \mathbf{F}$$

/Fred

Last edited: Feb 5, 2006
2. Feb 5, 2006

HallsofIvy

Did you miswrite something? What matrix expression?

3. Feb 6, 2006

Mathman23

No, It is correctly typed.

/Fred

4. Feb 6, 2006

<NAME>

You did mistype something. s appears in the last three symbols and nowhere before, and the X vanishes from the question.

Last edited: Feb 6, 2006
5. Feb 6, 2006

HallsofIvy

When I first looked at it there was no matrix expression! May have been the server was slow in loading the LATEX. However, as Matt said, "if and only if $$s \in \mathbf{F}$$ makes no sense as there is no "s" in the hypothesis.


text:
# Teaching

### Courses

EC 201: Principles of Microeconomics

Description: The purpose of this course is to cultivate economic intuition. My goal is not to teach students what to think, but rather how to think as economists. The course considers how social outcomes are shaped by the decisions of many individuals, even though each individual commands only a small fraction of the economy. Expanding upon the notion that individuals respond to incentives, students will use models to analyze and assess a variety of social phenomena. Successful students will leave the course with an intellectual framework for understanding and evaluating economic issues and policy.
Instructor of Record: Winter 2019, Winter 2020
Teaching Assistant: Spring 2017, Spring 2018, Fall 2018, Spring 2019

EC 320: Introduction to Econometrics

Description: This course introduces the statistical techniques that help economists learn about the world using data. Using calculus and introductory statistics, students will cultivate a working understanding of the theory underpinning regression analysis–how it works, why it works, and when it can lead us astray. As the course progresses, students will apply the insights of theory to work with and learn from actual data using R, a statistical programming language. My goal is for students to leave the course with marketable skills in data analysis and–most importantly–a more sophisticated understanding of the notion that correlation does not necessarily imply causation.
Instructor of Record: Summer 2019, Fall 2019

EC 350: Labor Economics

Description: This course applies insights from economic theory and real-world data to explore the causes of inequality in the labor market. Building upon concepts from introductory microeconomics, we will analyze the responses of workers and employers to changes in incentives, and consider the roles of policy, institutions, and other social phenomena in shaping labor market outcomes. As part of this line of inquiry, we will develop a toolkit that integrates theory and data, paying special attention to the ways in which we can identify–or fail to identify–causal relationships from data. Beyond refining their understanding of mechanisms that drive income inequality, successful students will leave the course with a framework for evaluating evidence and policy.
Instructor of Record: Summer 2018, Spring 2021, Winter 2022

EC 101: Contemporary Economic Issues

Teaching Assistant: Fall 2016, Fall 2017


text:
# What is the period of f(theta) = tan ( ( 17 theta)/12 )- cos ( ( 3 theta)/ 4 ) ?

Jul 23, 2017

$24 \pi$.

#### Explanation:

You need to find the smallest number of periods so that both functions have undergone an integer number of wavecycles.

$\frac{17}{12} \cdot n = {k}_{0}$ and $\frac{3}{4} \cdot n = {k}_{1}$ for some $n , {k}_{0} , {k}_{1} \in Z +$.

It is obvious by considering the denominators that $n$ should be chosen to be $12$. Then each of the two functions have had a whole number of wave cycles every 12 wave cycles.

12 wave cycles at $2 \pi$ per wave cycle gives a period of $24 \pi$.


text:
# TimeSeriesTest¶

class hyppo.time_series.base.TimeSeriesTest(compute_distance=None, max_lag=0, **kwargs)

A base class for a time-series test.

Parameters
• compute_distance (str, callable, or None, default: "euclidean") -- A function that computes the distance among the samples within each data matrix. Valid strings for compute_distance are, as defined in sklearn.metrics.pairwise_distances,

• From scikit-learn: ["euclidean", "cityblock", "cosine", "l1", "l2", "manhattan"] See the documentation for scipy.spatial.distance for details on these metrics.

• From scipy.spatial.distance: ["braycurtis", "canberra", "chebyshev", "correlation", "dice", "hamming", "jaccard", "kulsinski", "mahalanobis", "minkowski", "rogerstanimoto", "russellrao", "seuclidean", "sokalmichener", "sokalsneath", "sqeuclidean", "yule"] See the documentation for scipy.spatial.distance for details on these metrics.

Set to None or "precomputed" if x and y are already distance matrices. To call a custom function, either create the distance matrix before-hand or create a function of the form metric(x, **kwargs) where x is the data matrix for which pairwise distances are calculated and **kwargs are extra arguements to send to your custom function.

• max_lag (float, default: 0) -- The maximium lag to consider when computing the test statistics and p-values.

• **kwargs -- Arbitrary keyword arguments for compute_distance.

Methods Summary

 Calulates the time-series test statistic. TimeSeriesTest.test(x, y[, reps, workers, ...]) Calulates the time-series test test statistic and p-value.

abstract TimeSeriesTest.statistic(x, y)

Calulates the time-series test statistic.

Parameters

x,y (ndarray of float) -- Input data matrices. x and y must have the same number of samples. That is, the shapes must be (n, p) and (n, q) where n is the number of samples and p and q are the number of dimensions. Alternatively, x and y can be distance matrices, where the shapes must both be (n, n).

abstract TimeSeriesTest.test(x, y, reps=1000, workers=1, random_state=None)

Calulates the time-series test test statistic and p-value.

Parameters
• x,y (ndarray of float) -- Input data matrices. x and y must have the same number of samples. That is, the shapes must be (n, p) and (n, q) where n is the number of samples and p and q are the number of dimensions. Alternatively, x and y can be distance matrices, where the shapes must both be (n, n).

• reps (int, default: 1000) -- The number of replications used to estimate the null distribution when using the permutation test used to calculate the p-value.

• workers (int, default: 1) -- The number of cores to parallelize the p-value computation over. Supply -1 to use all cores available to the Process.

Returns


text:
# Version 0.2 (latest)¶

A file conforming to the openEPDA data format has the following structure. The first line is a format identifier, # openEPDA DATA FORMAT. After this, the data part follows, which contains two sections. The first section adheres to the YAML format, and contains all scalar (numeric and textual) data in the name: value form. This format is applicable for storing all previously mentioned types of the data. The second section is a CSV-formatted (RFC 4180 CSV Files) part to store the tabular measurement data.

An example of a file recorded in the openEPDA data format is shown below. Line 1 specifies the file format. Lines 2 to 16 contain metadata in YAML-format, including the values for two reserved keys. Here, only string and float data types are used, however arrays and maps can also be included. Line 18 contains a standard document-end marker. Lines 19 to the end of the document contain the CSV-formatted tabular data with a single header line.

## Attributes¶

### Reserved¶

The following keys have a special meaning:

• _timestamp: time the data was created in ISO format.

• _openEPDA_version: string defining the format version, e.g. '0.2'

## Example data file¶

Line number

File contents

1

# openEPDA DATA FORMAT

2

_timestamp: '2018-09-12T09:59:19.310182'

3

_openEPDA_version: '0.2'

4

project: OpenPICs

5

setup: RF setup

6

operator: Xaveer

7

wafer: 36386X

8

sample: 13L8

9

cell: SP35-1-3

10

circuit: MSSOA1-6

11

'current_density, kA/cm**2': 1

12

'reverse_bias, V': -2

13

configuration: 1

14

polarization: TE

15

port: 'ioE132'

16

'chip_temperature, degC': 18

17

'water_temperature, degC': 14

18

...

19

"wavelength, nm","transmitted power, dBm"

20

1550.0000000000000e+00,-21.000000000000000e+00

21

1551.0000000000000e+00,-22.000000000000000e+00


text:
## Diagonalize Matrix, Given an Eigenvalue and Eigenvector

1. The problem statement, all variables and given/known data

$$\begin{bmatrix} -7 && -16 && 4\\ 6 && 13 && -2\\ 12 && 16 && 1 \end{bmatrix}$$

Diagonalize the matrix (if possible), given that one eigenvalue is 5, and that one eigenvector is {-2, 1, 2}

2. Relevant equations

$$A=PDP^{-1}$$

3. The attempt at a solution

If I were allowed to simply calculate the eigenvalues and corresponding eigenvectors, I'd be able to determine if it's diagonalizable and if so, to diagonalize it. The problem here is that I have to go only on the provided information.

I'm stuck regarding how to proceed with this question. Where do I start?

Thanks!

 PhysOrg.com science news on PhysOrg.com >> Hong Kong launches first electric taxis>> Morocco to harness the wind in energy hunt>> Galaxy's Ring of Fire
 Mentor Start by finding the eigenvalue associated with the given eigenvector and determining what system of equations the eigenvector for λ=5 has to satisfy.
 Oh! I just read the question wrong. I assumed that the eigenvector provided was in the eigenspace of the provided eigenvalue. That probably means there will be two eigenvalues, and one of them will have an algebraic multiplicity of 2. I'll give it a shot and see if that works. Thanks. :) Edit: Well that was easy! Perhaps I should spend more time reading these questions :P Thanks!

Recognitions:
Gold Member
Staff Emeritus

## Diagonalize Matrix, Given an Eigenvalue and Eigenvector

 Quote by BraedenP Oh! I just read the question wrong. I assumed that the eigenvector provided was in the eigenspace of the provided eigenvalue.
Well, that obviously is NOT true because (-7)(-2)+ (-16)(1)+ (4)(2)= 14- 16+ 8= 6, not -10.

 That probably means there will be two eigenvalues, and one of them will have an algebraic multiplicity of 2. I'll give it a shot and see if that works. Thanks. :) Edit: Well that was easy! Perhaps I should spend more time reading these questions :P Thanks!
Why did you say "If I were allowed to simply calculate the eigenvalues and corresponding eigenvectors"? There is nothing in the statement of the problem that prohibits that. The characteristic equation is cubic and knowing one solution allows you to reduce it to a quadratic.

 Quote by HallsofIvy Well, that obviously is NOT true because (-7)(-2)+ (-16)(1)+ (4)(2)= 14- 16+ 8= 6, not -10. Why did you say "If I were allowed to simply calculate the eigenvalues and corresponding eigenvectors"? There is nothing in the statement of the problem that prohibits that. The characteristic equation is cubic and knowing one solution allows you to reduce it to a quadratic.
Regarding your first point, I didn't actually calculate anything; I just took it by assumption (yes, bad.. I know) that the eigenvector and value were associated.

Regarding the second point, we were explicitly told not to calculate eigenvalues using the characteristic equation.

But it's all good now. Thanks :)

 Tags diagonalize, eigenspace, eigenvalue, eigenvector, matrix


text:
# std::vector question

## Recommended Posts

If I create a two dimensional std::vector (4x4) like this: vector <vector<int> > LBlock(4, vector<int>(4)); Can I somehow initialize the elements in the vector like a normal array like this? I have to do this in order to get the order of the 0's and 1's the way I want it.
LBlock = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};

Question #2 Can I allot a two dimensional vector to a two dimensional array somehow. If this works, I don't have to worry about initializing the vectors the way I mentioned above. Neither vecBlock = arrBlock; or type casting works, is there any other way?

##### Share on other sites
(1) Is there a reason you don't want to use the standard push_back function to initialise your vector?
  for( int firstIndex = 0; firstIndex < 4; firstIndex++ ){  for( int secondIndex = 0; secondIndex < 4; secondIndex++ )  {     (LBlock[firstIndex]).push_back( 0 );  }}

(2) Depending on the size of your arrays and vectors you could just loop through the elements.

Cheers
Amos

##### Share on other sites
[EDIT - Sorry Amos - you beat me to it [smile]]

I may be wrong, but I am pretty sure that the answer is no to both of those questions.

vector data is allocated on the heap, even when the vector itself is static, so if nothing else, that would preclude being able to initialise it with the syntax above.

And I am not aware of any implicit conversion from a 2D array to a vector of vectors. For a start, they have different properties - a 2D array is always rectangular but a vector of vectors is not.

It is fairly trivial to write such a converter though, so you could initialise a 2D array statically then, on start up, use a function to copy this into a vector of vectors.

int Data[3][3]={{ 0,1,0 },                { 1,0,1 },                { 0,1,0 }};std::vector<std::vector<int> > Vec;void Init(){    Vec.resize(3);    for(int Y=0;Y<3;++Y)        {        for(int X=0;X<3;++X)            {            Vec[Y].push_back(Data[Y][X])); // or is that Data[X][Y]? I can never remember            }        }}

I think that is right. I get a bit confused by 2D arrays and avoid them like the plague to be honest.

If your container is always going to be rectangluar, I understand that there is a boost::multidimensional_array (or something) that may be useful. Alternatively, here's a class I use for 2D game maps:

class Map{private:    std::vector<int> V; int W,H;public:    Map(int Width,int Height) : W(Width),H(Height) { V.resize(W*H); }    int &operator()(int X,int Y);    int operator()(int X,int Y) const;    int Width() const { return W; }    int Height() const { return H; }    class BoundsError{ };};int &Map::operator()(int X,int Y){    if(X<0 || X>=W || Y<0 || Y>=H) throw BoundsError();    return V[(Y*W)+X];}int Map::operator()(int X,int Y) const{    if(X<0 || X>=W || Y<0 || Y>=H) throw BoundsError();    return V[(Y*W)+X];}int main(){    Map map(10,10);    map(3,2)=23;    std::cout << map(9,4) << std::endl; // etc}

This approach maintains the invariant that your container is rectangular and it also guarantees that the data is contiguous in memory, which a vector of vectors does not.

<NAME>

##### Share on other sites
Quote:
 Can I somehow initialize the elements in the vector like a normal array like this?

No, only normal arrays can be initialized thus, although there is discussion about extending C++ in this direction.

Quote:
 Can I allot a two dimensional vector to a two dimensional array somehow.

No. For starters you don't have a 2D vector, but a vector of vectors, each of which exists independently and not really as an integral part of a 2D structure. The fact that those vectors have been themselves put in a vector is completely incidental from their point of view.

There do exist true multidimensional array classes, like boost::multi_array. Also, depending on how exactly you plan on using the data, the std::valarray class may be what you are looking for.

##### Share on other sites
I didn't realize I could put the push_backs into a function like that. That's probably the easiest way I can make it. Something like this:

void SetPiece(int Data[]) {    Vec.resize(3); // not sure what this line does though, can only guess :)    for(int Y=0;Y<4;++Y) {        for(int X=0;X<4;++X) {            piece[Y].push_back(Data[Y][X]));        }    }}SetPiece(LBlock);

Probably have to change it to a vector with vector's though, since i've used that in the program so far. I hope they extend the language and makes this possible though, I find it really useful sometimes. Thank you all.

##### Share on other sites
you could always use std::fill or std::fill_n:

http://support.roguewave.com/support/docs/sourcepro/edition9/html/stdlibref/fill.html

also, it might be "better" to just have a 1D vector and index it by ( x + MAX_Y * y ); nested vectors of the same type is just a lot of overhead for no real additional functionality.

-me

##### Share on other sites
Plus if you're going to be initialising your vector of vectors because you already know its dimensions do you really need a vector or would a 2D array suit your needs better?

Cheers
Amos

##### Share on other sites
Quote:
 Original post by passwordVec.resize(3); // not sure what this line does though, can only guess :)

Sets the size of the vector to 3. If there were originally fewer elements in the vector, the new elements are default-initialized. If there were more, the vector gets truncated.

Quote:
 Probably have to change it to a vector with vector's though, since i've used that in the program so far.

Incidentally, if you're only going to use the vector as a static array, you may be better off just using an array in the first place, or grab a STL array wrapper like boost::array or std::tr1::array (where available).

Quote:
 I hope they extend the language and makes this possible though, I find it really useful sometimes. Thank you all.

If you are curious, check out the current discussion. For more, go here and scroll down to or search for the papers about "Initializer lists".

[Edited by - Fruny on October 9, 2006 5:58:41 PM]

##### Share on other sites
Hey I dont got any live code but I can tell you somethin, im making a game that is using a PLETHORA of multidimentional[sic] vectors in it.
The way I make a normal vector behave like a multidimensional one is to create a width variable and use that to controll moving "up" and "down".
Heres the logic like so.

vector <int> board(9, 0);for (int i = 0;i < board.size(); i++)    display board[i];This gets displayed.000000000int boardWidth = 3;int j = 1;for (int i = 0;i < board.size(); i++){    display board[i];    j++;    if (j == boardWidth)       newline;}This gets displayed.000000000

if you wanted to move something up or down on the board, you simply add or subtract the width of the board.

if you want to use X and Y coordinates heres an little algorithm I made that will convert a vector location into X and Y coordinated, and another one that will take X and Y coordinated and convert them into a vector spot.

Here this takes a vector location and makes it into x and y coordinated.
int x = vector loacation + 1;int y = 0;while (x > boardWidth){        x -= boardWidth;	y++;}

This will take X and Y coordinates and return a vector location.
int XY(int x, int y, boardWidth){	x--;	y--;		while (y > 0)		{			y--;			x += boardWidth;		}	return x;}

so you could do...
board[XY(1,1,3)] = 1;orboard[5] = 1;

both are the same thing.

Hope I was of some assistance.

##### Share on other sites
Not meaning to knock your code, Kaanin, but your functions to convert could be far more simply written and avoid loops all together:

int XYtoIndex(int X,int Y,int Width){    return (Y*Width)+X;}void IndextoXY(int Index,int Width,int &X,int &Y){    X=Index%Width;    Y=Index/Width;}

##### Share on other sites
You could just wrap the whole thing up in a class like so.
template<typename T>class Array2D{    std::vector<T> vec;    int Width, Height;public:    Array2D()  : Width(0), Height(0)    {}    Array2D(int W, int H)  : Width(W), Height(H)    {        vec.resize(Width*Height);            }    void Resize(int W, int H)     {        Widht = W;        Hwight = H;        vec.resize(Width*Height);    }    T& Index(int row, int column)    {        return Vec[column*Width + row]    }};

Probably want to add some bounds checking to Index()

##### Share on other sites
Quote:
 Original post by EasilyConfusedNot meaning to knock your code, Kaanin, but your functions to convert could be far more simply written and avoid loops all together:int XYtoIndex(int X,int Y,int Width){ return (Y*Width)+X;}void IndextoXY(int Index,int Width,int &X,int &Y){ X=Index%Width; Y=Index/Width;}

Ew, reference parameters for something like that?

typedef std::pair<int, int> xy;inline int XYtoIndex(xy XY, int width) {  return (XY.second * Width) + XY.first;}inline int XYtoIndex(int x, int y, int width) {  return XYtoIndex(std::make_pair(x, y), width);}inline xy IndextoXY(int index, int width) {  return std::make_pair(index % width, index / width);}

##### Share on other sites
[grin]

It was just an example (mutter mutter).

##### Share on other sites
I have one last problem with vectors right now. I want to push_back a 2d array into a vector just like you would push_back a class into a vector.

This works fine if I add a pointer to an int as datatype.
int arr[4] = {45,1,22,7};    vector<int*> Vec;Vec.push_back(arr);    for (int i=0;i<4;i++)    cout << Vec[0][i] << endl;

The same program using two dimensional array doesn't work however.
int arr[4][4] = {{45,1,22,7},                 {1,3,3,7},                 {0,55,123,44},                 {95,13,52,13}};    vector<int*> Vec;Vec.push_back(arr);    for (int i=0;i<4;i++)    cout << Vec[0][i] << endl;

Using a one dimensional array is not an option in this case, since the whole program is made to work with 2d arrays. Containing the arrays themselves shouldn't be a problem, but the compiler doesn't agree with me. Any way to contain 2d arrays with vector so I can refer to the arrays like this?

Vec[0] = 2d array 1
Vec[1] = 2d array 2
Vec[2] = 2d array 3
....

##### Share on other sites
Doubtful. When you define the type of a 2D array, you have to provide the size of the second subscript, so that the compiler can do the necessary math to resolve the index when you dereference:

int f(int a[][3]){    cout << a[1][2]; // couldn't work this out without the 3 above}

I just tried:

std::vector<int[][3]> v;

and got a load of "not an allowed type" errors.

The thing is that in your first example with a 1D array vector, you are not really pushing a 1D array into the vector, you are just pushing a pointer to the start of the array. The array name decomposes down to a pointer to the start of the array when it is passed as a parameter of such type to push_back.

A pointer can be used pretty much interchangabley with a 1D array. The same is not true of a 2D array so I think you are out of luck.

I'm not sure if you will like this, but the following code shows how you can create a class that uses a single normal pointer to memory but allows for access via [][] like a 2D array. You could use a technique like this, or find a third-party container (boost?) that does a similar thing, then "silently" replace all your 2D arrays at declaration with such a class so the rest of your code is not affected:

#include <iostream>class array{private:    int *p,w,h;class sub{private:    array *owner; int i;public:    sub(array *a,int v) : owner(a),i(v) { }    int &operator[](int v){ return owner->val(i,v); }};public:    array(int wt,int ht) : w(wt),h(ht) { p=new int[w*h]; }    ~array(){ delete [] p; }    int &val(int x,int y){ return p[(y*w)+x]; }    sub operator[](int i){ return sub(this,i); }};int main(){    array a(3,3);    int i=0;    for(int y=0;y<3;++y)        {        for(int x=0;x<3;++x)            {            a[x][y]=i++;            }        }    for(int y=0;y<3;++y)        {        for(int x=0;x<3;++x)            {            std::cout << a[x][y] << " ";            }        std::cout << std::endl;        }    return 0;}

With something like that, you could certainly have a std::vector<array>, although you'd need to supply array with a default constructor and a resize method so you could resize the individual arrays after the vector had been initialised.

You could then do:

std::vector<array> v;v.resize(1);v[0].resize(3,3);v[0][1][2]=3;

However, just because something is possible doesn't mean it is a good design [smile].

HTH Paul

##### Share on other sites
Quote:
 Original post by EasilyConfusedDoubtful. When you define the type of a 2D array, you have to provide the size of the second subscript, so that the compiler can do the necessary math to resolve the index when you dereference:int f(int a[][3]){ cout << a[1][2]; // couldn't work this out without the 3 above}I just tried:std::vector v;and got a load of "not an allowed type" errors.The thing is that in your first example with a 1D array vector, you are not really pushing a 1D array into the vector, you are just pushing a pointer to the start of the array. The array name decomposes down to a pointer to the start of the array when it is passed as a parameter of such type to push_back. A pointer can be used pretty much interchangabley with a 1D array. The same is not true of a 2D array so I think you are out of luck.I'm not sure if you will like this, but the following code shows how you can create a class that uses a single normal pointer to memory but allows for access via [][] like a 2D array. You could use a technique like this, or find a third-party container (boost?) that does a similar thing, then "silently" replace all your 2D arrays at declaration with such a class so the rest of your code is not affected:*** Source Snippet Removed ***With something like that, you could certainly have a std::vector, although you'd need to supply array with a default constructor and a resize method so you could resize the individual arrays after the vector had been initialised.You could then do:std::vector v;v.resize(1);v[0].resize(3,3);v[0][1][2]=3;However, just because something is possible doesn't mean it is a good design [smile].HTH Paul

Thank you for writing all that code up. But from what it sounds from the last thread when I asked for something else, this thing that i'm about to do should be quite simple.

I'm currently making a Tetris game and want to make rotation for the blocks. So far, this is how it looks.

// the current piece (4x4)vector<vector<int> > piece(4, vector<int>(4));// the blocks i'm using in their first form    int LBlock0[4][4] = {{0, 1, 0, 0},                         {0, 1, 0, 0},                         {0, 1, 0, 0},                         {0, 1, 1, 0}};    int IBlock0[4][4] = {{0, 1, 0, 0},                         {0, 1, 0, 0},                         {0, 1, 0, 0},                         {0, 1, 0, 0}};             int LBlockMirror0[4][4] = {{0, 0, 1, 0},                               {0, 0, 1, 0},                               {0, 0, 1, 0},                               {0, 1, 1, 0}};        int SquareBlock0[4][4] = {{0, 0, 0, 0},                              {0, 1, 1, 0},                              {0, 1, 1, 0},                              {0, 0, 0, 0}};    int ArrowBlock0[4][4] = {{1, 1, 1, 0},                             {0, 1, 0, 0},                             {0, 0, 0, 0},                             {0, 0, 0, 0}};

Going from an advice from another thread, I will make the rotation by changing the index of an array that holds all the blocks of the current kind. My way of solving this is to make a global variable named "rotation" which is going to have a value between 0-3 which represents the index/rotation of the current block.

Then I thought I could do it some way like this. LBlock[rotation]; supposed the LBlock vector/array contains all the 4 different forms of the LBlock.

I also have a switch statement in the function that generates a new block. That switch checks which block is going to be next. If the switch is for example 0 (random number), the currentblock is set to LBlock[0]; where 0 is the normal rotation of the block. When I later on Blit the blocks on the screen I use the rotation variable like this, LBlock[rotation]. rotation=0 if the player hasn't pushed the up button which changes the value.

The reason I mentioned the switch case is because I want to somehow set the vector to the block like this:

Vec = LBlock[0];
Vec = SquareBlock[0];
...

Well, anyways, the important part is how to store the 2d arrays somewhere so I can use them like I mentioned in combination with the rotation variable.

How would you make this in a simple way? I realized I should've asked this instead, because my first attempt may be too odd where I wanted to store 2d arrays in vectors.

##### Share on other sites
It has just occured to me, and I should have suggested this before really - you can't have a vector of 2D arrays, but you can have a vector of structs containing 2D arrays:

#include <iostream>#include <vector>struct Block{Block(int D[][3]);int Data[3][3];};Block::Block(int D[][3]){    for(int Y=0;Y<3;++Y)        {        for(int X=0;X<3;++X)            {            Data[X][Y]=D[X][Y];            }        }}typedef std::vector<Block> Blocks;std::vector<Blocks> v;int B[3][3]={ { 1,1,1 },              { 1,0,0 },              { 1,0,0 } };int main(){    v.resize(8);    v[0].push_back(Block(B));    for(int Y=0;Y<3;++Y)        {        for(int X=0;X<3;++X)            {            std::cout << v[0][0].Data[X][Y] << " ";            }        std::cout << std::endl;        }    return 0;}

Perhaps you can base your solution round that, although it will involve some changes to your existing code.

##### Share on other sites
One option is to use an array class wrapper of sorts (Boost has some).
Another option is to wrap the 2D array representing the block into an object, and store that instead:

class Block{  public:    // ...etc...  private:    int  mData[4 * 4];  // Could be [4][4] if you really want...};

Then use a std::vector of Block. This is a much more robust solution than trying to store raw arrays into a vector, since it isolates the implementation detail of a block (with appropriate accessors, such as an overloaded operator() or a get(x,y) method, you can implement the underlying storage however you like - an array, like I did, a 2D array, another vector, whatever). It also allows you to expand block to include extra methods and properties without having to create parallel-storage vectors. You could even move the information about the blocks rotations -- all of which can be calculated directly from a template block in a fixed orientation -- into the Block class and thus remove the need for the original vector (which seems geared towards storing just block rotations) entirely.

##### Share on other sites
That will indeed work, good ideas. I actually had a similar idea, but never followed up on it for some reason. I realized now it will work though.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628281
• Total Posts
2981801

• 10
• 11
• 17
• 14
• 9


text:
Irreducible Polynomials Over A Field

• January 20th 2011, 08:02 PM
Shapeshift
Irreducible Polynomials Over A Field
Are the polynomials in f(x) = x^3 + 2x^2 + 1 and g(x) = x^2 + x + 1 irreducible in F5[x]? Why or why not?

I'm having trouble checking to see if they are irreducible or not. I know it has something to do with the roots but I'm not too sure. Any help would be appreciated.
• January 20th 2011, 08:22 PM
tonio
Quote:

Originally Posted by Shapeshift
Are the polynomials in f(x) = x^3 + 2x^2 + 1 and g(x) = x^2 + x + 1 irreducible in F5[x]? Why or why not?

I'm having trouble checking to see if they are irreducible or not. I know it has something to do with the roots but I'm not too sure. Any help would be appreciated.

Hint: Over any field, a polynomial of degree less than or equal 3 (three) is irreducible iff it has no root in the field.

Tonio
• January 20th 2011, 08:27 PM
Shapeshift
So am I right in thinking that both f(x) and g(x) are irreducible since none of their roots = 0 (mod 5)?
• January 20th 2011, 08:30 PM
tonio
Quote:

Originally Posted by Shapeshift
So am I right in thinking that both f(x) and g(x) are irreducible since none of their roots = 0 (mod 5)?

I supose you meant "...since none of the elements of the field $\mathbb{F}_5$ is a root of any of them", and then yes: you'd be right.

Tonio
• January 20th 2011, 08:32 PM
Shapeshift
Haha sorry, I'm new to this concept so I'm still having a little trouble truly understanding it. Thank you!