text:
Feeds:
Posts

## A Simple Stochastic Climate Model: Climate Sensitivity

Last time I derived the following ODE for temperature T at time t:

where S and τ are constants, and F(t) is the net radiative forcing at time t. Eventually I will discuss each of these terms in detail; this post will focus on S.

At equilibrium, when dT/dt = 0, the ODE necessitates T(t) = S F(t). A physical interpretation for S becomes apparent: it measures the equilibrium change in temperature per unit forcing, also known as climate sensitivity.

A great deal of research has been conducted with the aim of quantifying climate sensitivity, through paleoclimate analyses, modelling experiments, and instrumental data. Overall, these assessments show that climate sensitivity is on the order of 3 K per doubling of CO2 (divide by 5.35 ln 2 W/m2 to convert to warming per unit forcing).

The IPCC AR4 report (note that AR5 was not yet published at the time of my calculations) compared many different probability distribution functions (PDFs) of climate sensitivity, shown below. They follow the same general shape of a shifted distribution with a long tail to the right, and average 5-95% confidence intervals of around 1.5 to 7 K per doubling of CO2.

Box 10.2, Figure 1 of the IPCC AR4 WG1: Probability distribution functions of climate sensitivity (a), 5-95% confidence intervals (b).

These PDFs generally consist of discrete data points that are not publicly available. Consequently, sampling from any existing PDF would be difficult. Instead, I chose to create my own PDF of climate sensitivity, modelled as a log-normal distribution (e raised to the power of a normal distribution) with the same shape and bounds as the existing datasets.

The challenge was to find values for μ and σ, the mean and standard deviation of the corresponding normal distribution, such that for any z sampled from the log-normal distribution,

Since erf, the error function, cannot be evaluated analytically, this two-parameter problem must be solved numerically. I built a simple particle swarm optimizer to find the solution, which consistently yielded results of μ = 1.1757, σ = 0.4683.

The upper tail of a log-normal distribution is unbounded, so I truncated the distribution at 10 K, consistent with existing PDFs (see figure above). At the beginning of each simulation, climate sensitivity in my model is sampled from this distribution and held fixed for the entire run. A histogram of 106 sampled points, shown below, has the desired characteristics.

Histogram of 106 points sampled from the log-normal distribution used for climate sensitivity in the model.

Note that in order to be used in the ODE, the sampled points must then be converted to units of Km2/W (warming per unit forcing) by dividing by 5.35 ln 2 W/m2, the forcing from doubled CO2.

## A Simple Stochastic Climate Model: Deriving the Backbone

Last time I introduced the concept of a simple climate model which uses stochastic techniques to simulate uncertainty in our knowledge of the climate system. Here I will derive the backbone of this model, an ODE describing the response of global temperature to net radiative forcing. This derivation is based on unpublished work by Nathan Urban – many thanks!

In reality, the climate system should be modelled not as a single ODE, but as a coupled system of hundreds of PDEs in four dimensions. Such a task is about as arduous as numerical science can get, but dozens of research groups around the world have built GCMs (General Circulation Models, or Global Climate Models, depending on who you talk to) which come quite close to this ideal.

Each GCM has taken hundreds of person-years to develop, and I only had eight weeks. So for the purposes of this project, I treat the Earth as a spatially uniform body with a single temperature. This is clearly a huge simplification but I decided it was necessary.

Let’s start by defining T1(t) to be the absolute temperature of this spatially uniform Earth at time t, and let its heat capacity be C. Therefore,

$C \: T_1(t) = E$

where E is the change in energy required to warm the Earth from 0 K to temperature T1. Taking the time derivative of both sides,

$C \: \frac{dT_1}{dt} = \frac{dE}{dt}$

Now, divide through by A, the surface area of the Earth:

$c \: \frac{dT_1}{dt} = \frac{1}{A} \frac{dE}{dt}$

where c = C/A is the heat capacity per unit area. Note that the right side of the equation, a change in energy per unit time per unit area, has units of W/m2. We can express this as the difference of incoming and outgoing radiative fluxes, I(t) and O(t) respectively:

$c \: \frac{dT_1}{dt} = I(t)- O(t)$

By the Stefan-Boltzmann Law,

$c \: \frac{dT_1}{dt} = I(t) - \epsilon \sigma T_1(t)^4$

where ϵ is the emissivity of the Earth and σ is the Stefan-Boltzmann constant.

To consider the effect of a change in temperature, suppose that T1(t) = T0 + T(t), where T0 is an initial equilibrium temperature and T(t) is a temperature anomaly. Substituting into the equation,

$c \: \frac{d(T_0 + T(t))}{dt} = I(t) - \epsilon \sigma (T_0 + T(t))^4$

Noting that T0 is a constant, and also factoring the right side,

$c \: \frac{dT}{dt} = I(t) - \epsilon \sigma T_0^4 (1 + \tfrac{T(t)}{T_0})^4$

Since the absolute temperature of the Earth is around 280 K, and we are interested in perturbations of around 5 K, we can assume that T(t)/T0 ≪ 1. So we can linearize (1 + T(t)/T0)4 using a Taylor expansion about T(t) = 0:

$c \: \frac{dT}{dt} = I(t) - \epsilon \sigma T_0^4 (1 + 4 \tfrac{T(t)}{T_0} + O[(\tfrac{T(t)}{T_0})^2])$

$\approx I(t) - \epsilon \sigma T_0^4 (1 + 4 \tfrac{T(t)}{T_0})$

$= I(t) - \epsilon \sigma T_0^4 - 4 \epsilon \sigma T_0^3 T(t)$

Next, let O0 = ϵσT04 be the initial outgoing flux. So,

$c \: \frac{dT}{dt} = I(t) - O_0 - 4 \epsilon \sigma T_0^3 T(t)$

Let F(t) = I(t) – O0 be the radiative forcing at time t. Making this substitution as well as dividing by c, we have

$\frac{dT}{dt} = \frac{F(t) - 4 \epsilon \sigma T_0^3 T(t)}{c}$

Dividing each term by 4ϵσT03 and rearranging the numerator,

$\frac{dT}{dt} = - \frac{T(t) - \tfrac{1}{4 \epsilon \sigma T_0^3} F(t)}{\tfrac{c}{4 \epsilon \sigma T_0^3}}$

Finally, let S = 1/(4ϵσT03) and τ = cS. Our final equation is

$\frac{dT}{dt} = - \frac{T(t) - S F(t)}{\tau}$

While S depends on the initial temperature T0, all of the model runs for this project begin in the preindustrial period when global temperature is approximately constant. Therefore, we can treat S as a parameter independent of initial conditions. As I will show in the next post, the uncertainty in S based on climate system dynamics far overwhelms any error we might introduce by disregarding T0.

## A Simple Stochastic Climate Model: Introduction

This winter I took a course in computational physics, which has probably been my favourite undergraduate course to date. Essentially it was an advanced numerical methods course, but from a very practical point of view. We got a lot of practice using numerical techniques to solve realistic problems, rather than just analysing error estimates and proving conditions of convergence. As a math student I found this refreshing, and incredibly useful for my research career.

We all had to complete a term project of our choice, and I decided to build a small climate model. I was particularly interested in the stochastic techniques taught in the course, and given that modern GCMs and EMICs are almost entirely deterministic, it was possible that I could contribute something original to the field.

The basic premise of my model is this: All anthropogenic forcings are deterministic, and chosen by the user. Everything else is determined stochastically: parameters such as climate sensitivity are sampled from probability distributions, whereas natural forcings are randomly generated but follow the same general pattern that exists in observations. The idea is to run this model with the same anthropogenic input hundreds of times and build up a probability distribution of future temperature trajectories. The spread in possible scenarios is entirely due to uncertainty in the natural processes involved.

This approach mimics the real world, because the only part of the climate system we have full control over is our own actions. Other influences on climate are out of our control, sometimes poorly understood, and often unpredictable. It is just begging to be modelled as a stochastic system. (Not that it is actually stochastic, of course; in fact, I understand that nothing is truly stochastic, even random number generators – unless you can find a counterexample using quantum mechanics? But that’s a discussion for another time.)

A word of caution: I built this model in about eight weeks. As such, it is highly simplified and leaves out a lot of processes. You should never ever use it for real climate projections. This project is purely an exercise in numerical methods, and an exploration of the possible role of stochastic techniques in climate modelling.

Over the coming weeks, I will write a series of posts that explains each component of my simple stochastic climate model in detail. I will show the results from some sample simulations, and discuss how one might apply these stochastic techniques to existing GCMs. I also plan to make the code available to anyone who’s interested – it’s written in Matlab, although I might translate it to a free language like Python, partly because I need an excuse to finally learn Python.

I am very excited to finally share this project with you all! Check back soon for the next installment.

## Milestones

You may have already heard that carbon dioxide concentrations have surpassed 400 ppm. The most famous monitoring station, Mauna Loa Observatory in Hawaii, reached this value on May 9th. Due to the seasonal cycle, CO2 levels began to decline almost immediately thereafter, but next year they will easily blow past 400 ppm.

Of course, this milestone is largely arbitrary. There’s nothing inherently special about 400 ppm. But it’s a good reminder that while we were arguing about taxation, CO2 levels continued to quietly tick up and up.

In happier news, John Cook and others have just published the most exhaustive survey of the peer-reviewed climate literature to date. Read the paper here (open access), and a detailed but accessible summary here. Unsurprisingly, they found the same 97% consensus that has come up over and over again.

Cook et al read the abstracts of nearly 12 000 papers published between 1991 and 2011 – every single hit from the ISI Web of Science with the keywords “global climate change” or “global warming”. Several different people categorized each abstract, and the authors were contacted whenever possible to categorize their own papers. Using several different methods like this makes the results more reliable.

Around two-thirds of the studies, particularly the more recent ones, didn’t mention the cause of climate change. This is unsurprising, since human-caused warming has been common knowledge in the field for years. Similarly, seismology papers don’t usually mention that plate tectonics cause earthquakes, particularly in the abstracts where space is limited.

Among the papers which did express a position, 97.1% said climate change was human-caused. Again, unsurprising to anyone working in the field, but it’s news to many members of the public. The study has been widely covered in the mainstream media – everywhere from The Guardian to The Australian – and even President Obama’s Twitter feed.

Congratulations are also due to Andrew Weaver, my supervisor from last summer, who has just been elected to the British Columbia provincial legislature. He is not only the first-ever Green Party MLA in BC’s history, but also (as far as I know) the first-ever climate scientist to hold public office.

Governments the world over are sorely in need of officials who actually understand the problem of climate change. Nobody fits this description better than Andrew, and I think he is going to be great. The large margin by which he won also indicates that public support for climate action is perhaps higher than we thought.

Finally, my second publication came out this week in Climate of the Past. It describes an EMIC intercomparison project the UVic lab conducted for the next IPCC report, which I helped out with while I was there. The project was so large that we split the results into two papers (the second of which is in press in Journal of Climate). This paper covers the historical experiments – comparing model results from 850-2005 to observations and proxy reconstructions – as well as some idealized experiments designed to measure metrics such as climate sensitivity, transient climate response, and carbon cycle feedbacks.

## A Visit to NCAR

Last week I was lucky enough to attend the Second Workshop on Coupling Technologies for Earth System Models, held at the National Center for Atmospheric Research (NCAR) in Boulder, Colorado, USA. I was excited just to visit NCAR, which is one of the top climate research facilities in the world. Not only is it packed full of interesting scientists and great museum displays, but it’s nestled in the Rocky Mountains and so the view from the conference room looks like this:

Many of the visitors would spend large portions of the coffee breaks just staring out the window…

The conference was focused on couplers – the part of a climate model that ties all the other components (atmosphere, ocean, land, etc.) together. However, the presentations covered (as Rob Jacob put it) “everything that physical scientists don’t care about unless it stops working”. Since I consider myself a physical scientist, this included a lot of concepts I hadn’t thought about before:

• Parallel processing: Since climate models are so big, it makes sense to multitask by splitting the work over many computer processors. You have to allocate the right number of processors to each component, though: if the atmosphere has too many processors, it will finish its timestep too quickly and sit there waiting until the ocean is done, and vice versa. This is called load balancing, and it gets very tricky as soon as the number of components exceeds two.
• Scalability: The more processors you use, the faster the model runs, but the speed has diminishing returns. If you double the number of processors, you won’t quite double the speed, particularly if the number of processors exceeds 104 (a setup which is becoming increasingly affordable for large research groups). Historically, the coupler has not been a code bottleneck (limiting factor for model speed), but as the number of processors gets very large, that scenario is changing. We have to figure out the most efficient way to couple many small components together, so that climate model speed can continue to keep up with advances in computer hardware.
• Standardization: Modelling groups across the world are communicating with each other more and more, and using each other’s code. Currently this requires a lot of modifications, because every climate model has a different structure. Everyone seems to agree that it would be great to have a standard interface that allowed you to plug any combination of components together, but of course everyone has a different idea of what that standard should be.
• Fortran is still the best language for climate models, believe it or not, because it is the fastest language for the kinds of operations required. If a modern, accessible language like Python could compete based on speed, you can bet that new climate models like MPAS would use it.

I was at the conference with Steve Easterbrook and his new M.Sc. student Daniel Levy, presenting our bubble diagrams of model architecture. (If you haven’t already, read my AGU poster schpiel first, or none of this will make sense!) As interesting and useful as these diagrams are, there were some flaws in our original analysis:

1. We didn’t use preprocessed code, meaning that each “model” is actually the code base for many different model configurations. So our estimate of model complexity based on line count is biased towards models which are very configurable, but might not actually be very complex. We can fix this by choosing specific configurations of each model (for consistency, the configuration used in CMIP5 or the equivalent EMIC AR5 intercomparison project) and obtaining preprocessed code from the corresponding institutions.
2. We sorted the code into components (eg atmosphere) and sub-components (eg atmospheric aerosols) based on folder structure, which might not reflect the hierarchy of routines formed at runtime. Some modelling groups keep their files very organized, but often code from different parts of the model was mixed together, and separating it out was very much a judgement call. To fix this, we can sort based on the dependency structure (a massive tree graph showing which routines call which): all the descendants of the atmosphere driver are part of the atmosphere component, and so on.
3. We made our diagrams in Microsoft PowerPoint, which is quite limited, and didn’t allow us to size the bubbles so their area was perfectly proportional to line count. Instead, we just had to eyeball it. We can fix this by using Adobe Illustrator, which is much more advanced and has this capability.

So far, we’ve repeated the analysis for the UK Met Office Model, version HadGEM2-ES. I created the dependency structure by going manually through every file and making good use of grep, which took hours and hours (although it was a nice, menial way to avoid studying for my courses!). Daniel is going to write a Fortran parser to make the job easier next time around. In the meantime, our HadGEM2-ES diagram is absolutely gorgeous and wonderfully accurate:

I will post future diagrams as they become available. We think the main use of these diagrams will be as communication tools between scientists, so they are free to use with attribution.

Just a few more weeks of classes, then I can enjoy some full-time research. Now that I’ve had a taste of being a proper scientist, it’s hard to go back!

Lately I have been reading a lot about the Paleocene-Eocene Thermal Maximum, or PETM, which is my favourite paleoclimatic event (is it weird to have a favourite?) This episode of rapid global warming 55 million years ago is particularly relevant to our situation today, because it was clearly caused by greenhouse gases. Unfortunately, the rest of the story is far less clear.

Paleocene mammals

The PETM happened about 10 million years after the extinction that killed the dinosaurs. The Age of Mammals was well underway, although humans wouldn’t appear in any form for another few million years. It was several degrees warmer, to start with, than today’s conditions. Sea levels would have been higher, and there were probably no polar ice caps.

Then, over several thousand years, the world warmed by between 5 and 8°C. It seems to have happened in a few bursts, against a background of slower temperature increase. Even the deep ocean, usually a very stable thermal environment, warmed by at least 5°C. It took around a hundred thousand years for the climate system to recover.

Such rapid global warming hasn’t been seen since, although it’s possible (probable?) that human-caused warming will surpass this rate, if it hasn’t already. It is particularly troubling to realize that our species has never before experienced an event like the one we’re causing today. The climate has changed before, but humans generally weren’t there to see it.

The PETM is marked in the geological record by a sudden jump in the amount of “light” carbon in the climate system. Carbon comes in different isotopes, two of which are most important for climate analysis: carbon with 7 neutrons (13C), and carbon with 6 neutrons (12C). Different carbon cycle processes sequester these forms of carbon in different amounts. Biological processes like photosynthesis preferentially take 12C out of the air in the form of CO2, while geological processes like subduction of the Earth’s crust take anything that’s part of the rock. When the carbon comes back up, the ratios of 12C to 13C are preserved: emissions from the burning of fossil fuels, for example, are relatively “light” because they originated from the tissues of living organisms; emissions from volcanoes are more or less “normal” because they came from molten crust that was once the ocean floor.

In order to explain the isotopic signature of the PETM, you need to add to the climate system either a massive amount of carbon that’s somewhat enriched in light carbon, or a smaller amount of carbon that’s extremely enriched in light carbon, or (most likely) something in the middle. The carbon came in the form of CO2, or possibly CH4 that soon oxidized to form CO2. That, in turn, almost certainly caused the warming.

There was a lot of warming, though, so there must have been a great deal of carbon. We don’t know exactly how much, because the warming power of CO2 depends on how much is already present in the atmosphere, and estimates for initial CO2 concentration during the PETM vary wildly. However, the carbon injection was probably something like 5 trillion tonnes. This is comparable to the amount of carbon we could emit today from burning all our fossil fuel reserves. That’s a heck of a lot of carbon, and what nobody can figure out is where did it all come from?

Arguably the most popular hypothesis is methane hydrates. On continental shelves, methane gas (CH4) is frozen into the ocean floor. Microscopic cages of water contain a single molecule of methane each, but when the water melts the methane is released and bubbles up to the surface. Today there are about 10 trillion tonnes of carbon stored in methane hydrates. In the PETM the levels were lower, but nobody is sure by how much.

The characteristics of methane hydrates seem appealing as an explanation for the PETM. They are very enriched in 12C, meaning less of them would be needed to cause the isotopic shift. They discharge rapidly and build back up slowly, mirroring the sudden onset and slow recovery of the PETM. The main problem with the methane hydrate hypothesis is that there might not have been enough of them to account for the warming observed in the fossil record.

However, remember that in order to release their carbon, methane hydrates must first warm up enough to melt. So some other agent could have started the warming, which then triggered the methane release and the sudden bursts of warming. There is no geological evidence for any particular source – everything is speculative, except for the fact that something spat out all this CO2.

Magnified foraminifera

Don’t forget that where there is greenhouse warming, there is ocean acidification. The ocean is great at soaking up greenhouse gases, but this comes at a cost to organisms that build shells out of calcium carbonate (CaCO3, the same chemical that makes up chalk). CO2 in the water forms carbonic acid, which starts to dissolve their shells. Likely for this reason, the PETM caused a mass extinction of benthic foraminifera (foraminifera = microscopic animals with CaCO3 shells; benthic = lives on the ocean floor).

Other groups of animals seemed to do okay, though. There was a lot of rearranging of habitats – species would disappear in one area but flourish somewhere else – but no mass extinction like the one that killed the dinosaurs. The fossil record can be deceptive in this manner, though, because it only preserves a small number of species. By sheer probability, the most abundant and widespread organisms are most likely to appear in the fossil record. There could be many organisms that were less common, or lived in restricted areas, that went extinct without leaving any signs that they ever existed.

Climate modellers really like the PETM, because it’s a historical example of exactly the kind of situation we’re trying to understand using computers. If you add a few trillion tonnes of carbon to the atmosphere in a relatively short period of time, how much does the world warm and what happens to its inhabitants? The PETM ran this experiment for us in the real world, and can give us some idea of what to expect in the centuries to come. If only it had left more data behind for us to discover.

## Climate Change and Atlantic Circulation

Today my very first scientific publication is appearing in Geophysical Research Letters. During my summer at UVic, I helped out with a model intercomparison project regarding the effect of climate change on Atlantic circulation, and was listed as a coauthor on the resulting paper. I suppose I am a proper scientist now, rather than just a scientist larva.

The Atlantic meridional overturning circulation (AMOC for short) is an integral part of the global ocean conveyor belt. In the North Atlantic, a massive amount of water near the surface, cooling down on its way to the poles, becomes dense enough to sink. From there it goes on a thousand-year journey around the world – inching its way along the bottom of the ocean, looping around Antarctica – before finally warming up enough to rise back to the surface. A whole multitude of currents depend on the AMOC, most famously the Gulf Stream, which keeps Europe pleasantly warm.

Some have hypothesized that climate change might shut down the AMOC: the extra heat and freshwater (from melting ice) coming into the North Atlantic could conceivably lower the density of surface water enough to stop it sinking. This happened as the world was coming out of the last ice age, in an event known as the Younger Dryas: a huge ice sheet over North America suddenly gave way, drained into the North Atlantic, and shut down the AMOC. Europe, cut off from the Gulf Stream and at the mercy of the ice-albedo feedback, experienced another thousand years of glacial conditions.

A shutdown today would not lead to another ice age, but it could cause some serious regional cooling over Europe, among other impacts that we don’t fully understand. Today, though, there’s a lot less ice to start with. Could the AMOC still shut down? If not, how much will it weaken due to climate change? So far, scientists have answered these two questions with “probably not” and “something like 25%” respectively. In this study, we analysed 30 climate models (25 complex CMIP5 models, and 5 smaller, less complex EMICs) and came up with basically the same answer. It’s important to note that none of the models include dynamic ice sheets (computational glacial dynamics is a headache and a half), which might affect our results.

Models ran the four standard RCP experiments from 2006-2100. Not every model completed every RCP, and some extended their simulations to 2300 or 3000. In total, there were over 30 000 model years of data. We measured the “strength” of the AMOC using the standard unit Sv (Sverdrups), where each Sv is 1 million cubic metres of water per second.

Only two models simulated an AMOC collapse, and only at the tail end of the most extreme scenario (RCP8.5, which quite frankly gives me a stomachache). Bern3D, an EMIC from Switzerland, showed a MOC strength of essentially zero by the year 3000; CNRM-CM5, a GCM from France, stabilized near zero by 2300. In general, the models showed only a moderate weakening of the AMOC by 2100, with best estimates ranging from a 22% drop for RCP2.6 to a 40% drop for RCP8.5 (with respect to preindustrial conditions).

Are these somewhat-reassuring results trustworthy? Or is the Atlantic circulation in today’s climate models intrinsically too stable? Our model intercomparison also addressed that question, using a neat little scalar metric known as Fov: the net amount of freshwater travelling from the AMOC to the South Atlantic.

The current thinking in physical oceanography is that the AMOC is more or less binary – it’s either “on” or “off”. When AMOC strength is below a certain level (let’s call it A), its only stable state is “off”, and the strength will converge to zero as the currents shut down. When AMOC strength is above some other level (let’s call it B), its only stable state is “on”, and if you were to artificially shut it off, it would bounce right back up to its original level. However, when AMOC strength is between A and B, both conditions can be stable, so whether it’s on or off depends on where it started. This phenomenon is known as hysteresis, and is found in many systems in nature.

This figure was not part of the paper. I made it just now in MS Paint.

Here’s the key part: when AMOC strength is less than A or greater than B, Fov is positive and the system is monostable. When AMOC strength is between A and B, Fov is negative and the system is bistable. The physical justification for Fov is its association with the salt advection feedback, the sign of which is opposite Fov: positive Fov means the salt advection feedback is negative (i.e. stabilizing the current state, so monostable); a negative Fov means the salt advection feedback is positive (i.e. reinforcing changes in either direction, so bistable).

Most observational estimates (largely ocean reanalyses) have Fov as slightly negative. If models’ AMOCs really were too stable, their Fov‘s should be positive. In our intercomparison, we found both positives and negatives – the models were kind of all over the place with respect to Fov. So maybe some models are overly stable, but certainly not all of them, or even the majority.

As part of this project, I got to write a new section of code for the UVic model, which calculated Fov each timestep and included the annual mean in the model output. Software development on a large, established project with many contributors can be tricky, and the process involved a great deal of head-scratching, but it was a lot of fun. Programming is so satisfying.

Beyond that, my main contribution to the project was creating the figures and calculating the multi-model statistics, which got a bit unwieldy as the model count approached 30, but we made it work. I am now extremely well-versed in IDL graphics keywords, which I’m sure will come in handy again. Unfortunately I don’t think I can reproduce any figures here, as the paper’s not open-access.

I was pretty paranoid while coding and doing calculations, though – I kept worrying that I would make a mistake, never catch it, and have it dredged out by contrarians a decade later (“Kate-gate”, they would call it). As a climate scientist, I suppose that comes with the job these days. But I can live with it, because this stuff is just so darned interesting.


text:
Limit of distributions of principal value

What is the limit in $D'(\mathbb{R})$ (i.e. in the distribution sense) of $$\lim_{t \rightarrow +\infty}\frac{e^{ixt}}{x+i0}$$ where $x+i0=p.v.(\frac{1}{x})-i\pi\delta(x)$ and $p.v.(\frac{1}{x})$ is the principal value function of $\frac{1}{x}.$ Thank you.

-
If $f_t = \frac{e^{ixt}}{x+i0}$, what do you mean with $f_t(\varphi)$ for a test function $\varphi$? –  Vobo Jan 30 '13 at 18:42
It is just $f_t(\phi)=\int \frac{e^{ixt}}{x+i0} \phi(x)dx$. –  Frank Zermelo Jan 30 '13 at 21:04
Do you mean $f_t(\varphi) = -i\pi \varphi(0) + \lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{e^{ixt}}{x}\varphi(x) dx$? –  Vobo Jan 30 '13 at 21:27
Yes, this is what I mean. –  Frank Zermelo Jan 30 '13 at 23:12
Is there a reason, why you do not comment the answer? –  Vobo Feb 3 '13 at 19:42

As clarified in the comment above, we need to calculate $$\lim_{t\to\infty}\lim_{\epsilon\to 0} \int_{|x|>\epsilon}\frac{e^{itx}}{x}\varphi(x) dx = \lim_{t\to\infty} \lim_{\epsilon\to 0}\int_{|x|>\epsilon} \frac{\cos tx}{x}\varphi(x) dx + i \lim_{t\to \infty} \lim_{\epsilon\to 0}\int_{|x|>\epsilon} \frac{\sin tx}{x}\varphi(x) dx.$$ The sinus integral converges to $\pi \varphi(0)$ as the integrand is continous at $0$. Using the substitution $tx\mapsto y$ and $\lim_{\epsilon\to 0}\int_{|x|>\epsilon} \frac{f(x)}{x} dx = \int_0^\infty \frac{f(x) - f(-x)}{x} dx$ the cosinus integral becomes $$\int_0^\infty \frac{\cos y}{y} (\varphi(\frac{y}{t}) - \varphi(-\frac{y}{t})) dy.$$ Splitting this integral into $\int_0^1 ...$ and $\int_1^\infty$, the latter converges to $0$ for $t\to\infty$ by the dominated convergence theorem. Applying the mean value theorem, the first integral becomes $$\int_0^1\frac{\cos y}{y}\frac{2y}{t} \varphi'(\xi_t) dy$$ for some $\xi_t\in [-t,t]$. As $\varphi'$ is bounded, for $t\to\infty$ this integral converges to $0$ too.
To summarize everything: $$\lim_{t\to\infty} \frac{e^{ixt}}{x+i0} = 0.$$
Well, I didn't comment your answer, because my busy schedule didn't allow me to. I apologize for the delay. In principle, it is the same proof I gave. Some few remarks however: $\frac{sin x}{x}$ is indeed continuous at 0, but it is not integrable, so the convergence of the first integral is not that obvious (at least, not for me). To justify the convergence, my suggestion would be to develop in the Taylor series, and to analyze the convergence of the first terms separately. Secondly, $\xi$ depends on $t$ and on $y$ as well, and actually $\xi \in [-y/t,y,t]$, but it doesn't matter a lot as it –  Frank Zermelo Feb 6 '13 at 10:12
$\phi'$ is bounded as you mentioned.I will post my solution too these days, not because I do not like your solution, but just to have more proofs for this nice fact. In the end, thank you for your proof and for contributing to this post. –  Frank Zermelo Feb 6 '13 at 10:13

format: plain


text:
# How do you graph y=tan(x+(7pi)/6)?

Nov 23, 2016

graph{y-tan(x+3.665)=0 [-10, 10, -5, 5]}

$y = \tan \left(\pi + \left(\frac{\pi}{6} + x\right)\right) = \tan \left(x + \frac{\pi}{6}\right)$

The period of y is $\pi$. !n the graph, the graph for one period

repeats in a cycle.

A convenient choice of one period is $x \in \left(- \frac{2}{3} \pi , \frac{\pi}{3}\right)$. $\pi = 3.14$

in the graph.

As x to pi/3, y to oo$and as x to -2/3pi, y to -oo#. $\left(- \frac{\pi}{6} , 0\right)\$ is in the middle of the graph, where the tangent

crosses the curve. It is called a point of inflexion. Here, y'' = 0.


text:
# $O(2)$ is isomorphic to $SO(2)\times\mathbb Z_2$ [duplicate]

If have proven that $$\frac{O(2)}{SO(2)}$$ is isomporphic to $$\mathbb Z_2$$.

Does is follow from this that $$O(2)$$ is isomorphic to $$SO(2)\times\mathbb Z_2$$

• Use \times not x for $\times$ in math mode. May 18 '20 at 14:06
• No. $\mathbb{Z}_4/\mathbb{Z}_2 = \mathbb{Z}_2$, but $\mathbb{Z}_4 \not = \mathbb{Z}_2\oplus \mathbb{Z}_2$. May 18 '20 at 14:08
• $SO(2)\times\Bbb{Z}_2$ is an abelian group. $O(2)$ is not. May 18 '20 at 14:12
• Something along the lines that you are thinking is the Schur–Zassenhaus theorem. May 18 '20 at 14:17


text:
# Meaning of $\frac{1}{\sqrt{dt}}$ in stochastic forcing

I am running a 2D fluids simulation with a stochastic forcing $$f$$ in a doubly-periodic box, i.e. solving

$$\frac{\partial \nabla^2 \psi}{\partial t} = J(\psi,\nabla^2 \psi) +f,$$ where $$J$$ is a Poisson bracket.

The forcing I've chosen is of the form

$$f= \sum_{k,l} c \sin(k x + \alpha_k) \sin(l y + \beta_l),$$ where the wavenumbers $$k$$ and $$l$$ are selected from a thin annulus centered at $$k_f$$ (a common prescription), and $$\alpha_k$$ and $$\beta_l$$ are phases which are in some sense stochastic (more on this later). (When $$k=0$$ or $$l=0$$ one needs a slightly different treatment but this is a minor detail).

One can show that $$\int d^2 x \, \psi \frac{\partial \nabla^2 \psi}{\partial t} = - \frac{\partial E}{\partial t}$$ where $$E$$ is the total kinetic energy. We can use this to compute the energy injection rate from the forcing:

$$\varepsilon = -\langle f \xi \rangle = \frac{N c^2}{4 k_f^2},$$ where $$\nabla^2 \xi = f$$ and $$N$$ is the number of wavevectors in the annulus. This motivates the choice $$c = 2 k_f\sqrt{\frac{\varepsilon}{N}}$$.

Now, we need to prescribe a temporal correlation for the forcing. The standard choice is white noise, i.e. $$f$$ is delta-correlated in time. In (for example) Appendix A of Srinivasan and Young (2012), the authors select the phases i.i.d. from a uniform distribution and aver that the forcing must be normalized by $$1/\sqrt{\delta t}$$ ($$\delta t$$ being the time-step of the integration algorithm) in order to ensure that it is delta-correlated. This raises two questions with which I'm struggling:

1. How, precisely, does this lead to delta-correlated forcing? I'm having some trouble showing it analytically.
2. What now of the energy injection rate? Isn't it altered by a factor of 1/$$\delta t$$? And aren't the dimensions now compromised?

Furthermore, as is pointed out in the same appendix, in a Runge-Kutta algorithm, the forcing must be kept reasonably smooth during the course of a time-step, so in that paper, they select the phases within a time-step by linear interpolation. I'm finding this tricky to implement with the library I'm using, so I had the idea to instead update the phases by their own random walk: $$\alpha_k(t+\delta t) = \alpha_k(t) + \sqrt{\delta t} \eta$$ with $$\eta\sim {\cal N}(0,\sigma^2),$$ and the same for the $$\beta_l$$. Then one can show that this leads to the correlation function

$$\langle f(\mathbf{x},0)f(\mathbf{x},t) \rangle = \frac{Nc^2}{4} \exp(-|t|/\tau)$$ where $$\tau= 1/\sigma^2$$. This forcing is nice in that it's nice and smooth and you can control the correlation time...unless you want white noise. Thus, a third question:

1. Can this forcing prescription be adjusted simply so that, in the limit $$\tau \to 0$$, the forcing is temporally white? Does, say, normalizing $$f$$ by $$1/\sqrt{\tau}$$ work?

Thanks in advance to anyone who can help me with this.

• To answer (what I understood is) the first point, you must make units right. Since $<\eta(t)\eta(t')>\propto\delta(t-t')$ units of $\eta$ are $1/\sqrt{t}$. When you inject it to the stochastic equation $dx=adt + bdt\eta$ the last term is actually proportional to $\sqrt{dt}$ Jun 4 '20 at 1:02
• I've thought about this more and it's easier for me to conceptualize in terms of the central limit theorem, which shows that, if $\partial_t \zeta = \xi(t)$ for some random $\xi$, $\zeta(\tau)-\zeta(0) \sim \sqrt{\tau \delta t} {\cal N} (0, \langle \xi^2 \rangle)$, so we need the normalization to ensure that $\langle \zeta^2 \rangle \sim t$ like a good Brownian motion. I'm still trying to figure out how this affects the rate of energy injection... Jun 4 '20 at 1:38
• I think I now roughly understand the energy injection issue. The rate of energy injection is not, as I wrote, $-\langle \xi f \rangle,$ but $-\langle \psi f \rangle$. It stands to reason, at least in a hand-waving sort of way, that $\psi \sim \sqrt{t} \xi$ (where again $\nabla^2 \xi = f$), so the rate of energy injection in fact is only constant in time once the normalization is introduced. Jun 4 '20 at 1:59
• Reading this paper aip.scitation.org/doi/pdf/10.1063/1.870050 helped me resolve these conceptual problems and identify my error Jun 4 '20 at 2:55
• consider posting it as an answer, with short description of the solution Jun 4 '20 at 5:13

The need for the normalization can be illustrated as follows. Consider only the contribution of the forcing: $$\partial_t \zeta = f(t).$$

If we discretize time in steps $$\delta t$$, $$f$$ is a sequence of iid random variables $$\{f_i\}$$ with mean 0. Then we have (setting $$\zeta(0)=0$$) $$\zeta(t) = \delta t \sum_i f_i.$$

According to the central limit theorem, for $$t\gg \delta t$$, we have $$\sum_i f_i \sim \sqrt{N}{\cal N}(0,\langle f^2 \rangle)$$ where $$N=t/\delta t$$. Thus

$$\zeta(t) \sim \sqrt{t \delta t} {\cal N}(0,\langle f^2 \rangle)$$ and it is evident that $$f$$ must be normalized by $$1/\sqrt{\delta t}$$ in order for its evolution to be independent of the timestep.

My issue with the energy injection rate largely stemmed from an error in calculation. The rate is $$\varepsilon = - \langle \psi f\rangle,$$ not $$-\langle \xi f \rangle$$ (where again, $$\nabla^2 \xi = f$$). Following K. Alvelius PoF 11, 1880 (1999), we have (considering only the forcing's contribution to the dynamics) $$\psi = \int_0^t d\tau \, \xi(\tau),$$ so $$\varepsilon = - \int_0^t d\tau \, \langle \xi(\tau)f(t) \rangle.$$

My previous, erroneous calculation did not have the correct units, and clearly missed a factor with dimensions of time. In the case of my implementation of the forcing, the energy injection rate follows as

$$\varepsilon =\frac{Nc^2}{4k_f^2} \tau_c (1- \exp(-|t|/\tau_c)$$.

After many correlation times, the second term is negligible and choosing $$c= 2 k_f \sqrt{\frac{\varepsilon}{N \tau_c}}$$ fixes a chosen rate $$\varepsilon$$. Note that factor $$1/\tau_c$$, previously missed. This normalization also ensures that in the limit $$\tau_c \to 0$$, the volume of the correlation function is correctly conserved and a delta function is obtained, as desired.


text:
## Edit or Add New Contents to Proof: (related to "Upper Bound of Harmonic Series Times Möbius Function") [8148]

You have to log in in order to edit or add new contents to the entries of BookofProofs.


text:
# Separation result for proper learning under the uniform vs. adversarial distributions?

Does anyone know of a concept class known to be (1) efficiently learnable under the uniform distribution but (1) NP-hard to learn under arbitrary [adversarial] distributions? I mean "learning" in the proper PAC sense.

Width-k conjunctions are NP hard to learn using halfspaces (and in particular using conjunctions) over arbitrary distributions, even for $k > \log(n)$: http://www.cs.cmu.edu/~yiwu/paper/mono.pdf
On the other hand, for $k \gg \log n$, width $k$ conjunctions are trivial to learn over the uniform distribution over examples using conjunctions, since every width-k conjunction will label a $1-1/2^k$ fraction of examples "0", so every width-k conjunction is a good hypothesis.
I would guess that there are similar examples that hold more broadly. Notice that easyness of learning over the uniform distribution holds for any "unbalanced" function, for the same trivial reason. Take a class of functions that is hard to learn even non-agnostically (poly-sized circuits, say). I would think that you could modify the lower-bound proof to hold even if you modify the circuits to be unbalanced: to evaluate to $1$ only on an $\epsilon$ fraction of random inputs. Meanwhile the hard distribution could still be one in which $\Pr[A(x) = 1] = 1/2$.
• Avrim Blum's answer via email: "2-term DNF. NP-hard for proper learning in general, but easy over the uniform distribution (find some $x_i$ s.t. $Pr(+|x_i=0) < Pr(+)$, and then $T_2 = {x_j : Pr(+ | x_i=0,x_j=0) = 0})$." – Aryeh Mar 14 '12 at 7:27
• I don't understand this comment: "since every width-k conjunction will label a $1-1/2^k$ fraction of examples 0, so every width-k conjunction is a good hypothesis." This does not seem to be true if $\epsilon$ is sufficiently small, i.e. $\epsilon < \frac{1}{2^k}$. In this case how would the learning algorithm proceed? – 6005 Apr 18 '20 at 18:38
• @Aryeh Can you clarify Blum's example? What is $T_2$? – 6005 Apr 18 '20 at 18:49
• @6005 We're talking about 2-term DNFs, i.e., expressions of the form $T_1\vee T_2$, where the $T_i$ are conjunctions of literals. – Aryeh Apr 18 '20 at 20:12


text:
# Standard deviation for a signal with a noise component

1. Sep 3, 2012

### ForceBoard

Hello,

I've been trying to find the answer to this question on the internet but no real luck so here goes:

Imagine a signal My_signal which has two components, the actual signal A which is not constant over time and a noise component, we can call it N, where said noise component has a standard deviation which is more or less constant over time regardless of the amplitude of A. How do I calculate the standard deviation for A?

If sigma is the standard deviation, is it:

My_signal = A + N

sigma(My_signal) = sqrt( (sigma(A)^2) + (sigma(N)^2))
-> sigma(A) = sqrt (sigma(My_signal)^2-sigma(N)^2))

Thanks,

Marcus

2. Sep 3, 2012

### chiro

Hey ForceBoard and welcome to the forums.

The first thing to ask is whether the signal is discrete time or continuous time.

If it is discrete time then you will need to consider how to sum the variances for each step to get the total variance over a time interval.

The easiest case happens when each individual part of the signal is independent, but this is not a feasible assumption in many cases because there are dependencies between the values of each part of the signal over the interval.

If it is continuous time, you do the same thing but depending on the properties it can be complex.

The simplest form of a continuous-time stochastic process is known as a thing called Brownian motion.

Brownian motion assumes that every disjoint interval is independent which simplifies things (like in the discrete case above) quite a bit: in fact all you have to do to find the variance of a typical Weiner Process is to look at the length of the interval. So if it's say an interval [0,1], then the variance of that process if the Weiner process starts at 0 with a value of 0 is 1 - 0 = 1.

Again though, this is not often feasible for signal analysis because signals often carry dependencies between different portions of the signals.

You will need to understand the context of the actual signal and the intrinsic structural properties of the signal with regard to what is actually being transported before you can answer this question.

To give you an idea think about the following situation:

You are trying to transmit digital data through some communication medium and suppose that a packet of data only gets transmitted once in one frame (basically a bunch of undivided data guaranteed to get to the destination by the requirements of the hardware, the channel, and so on).

Now in transmission, typically what happens is that you don't just send the minimum 1' and 0's: you add what is called an error correcting code. It can make the process send literally twice as much data but the point is to send these structures so that errors can be detected and in some cases corrected.

Depending on the noise model for the channel, you construct specific codes that minimize the errors by exploiting the noise models for the channel.

In the above case, things are not dependent: it's not just the noise model but the actual structure of the data since some of the data is dependent on the others.

This is a case where you can't just use the easiest assumption and this is more along the lines of a real situation than an ideal one.

3. Sep 3, 2012

### ForceBoard

Chiro, thank you for your elaborate response...

I'm actually looking at a signal from a force transducer where I can control the sampling rate between 10-50Hz, so I would say discrete time with an independent noise component.

As for the pure signal itself I think I would have to look at its segmens as being independent even if that is not completely true depending on the speed of the varying force I'm measuring and the physical nature of the force transducer.

More or less, no matter how much load I put on (using control weights) the standard deviation in the noise is maybe around 0.04. (Important to say that I don't know what type of statistical distribution the noise has, looks to be randomly jumping around a baseline)

As you already understand I'm interested in what the deviation of the pure signal is when the noise portion is cancelled out mathematically since that potentially can tell me alot about the test object interacting with the force tranducer.

4. Sep 3, 2012

### chiro

I am going to sleep soon, but you might want to check out the Weiner process first to get an idea of continuous time, independent normally distributed noise.

5. Sep 3, 2012

### Stephen Tashi

That is a correct formula. It's your general conception of the problem that needs improvement.

For a "random variable" X , the terms "standard deviation" can have several different meanings. Among these are

1. "Standard deviation" can refer to the standard deviation as a parameter of the probability distribution for X. This type of standard deviation can be called "the population standard deviation".

2. "Standard deviation" can refer to a number (like 0.43) that you calculate from a set of data for X, in which case it should be called a "sample standard deviation".

3. Both "standard deviation" and "sample standard deviation" can refer to a formula you use to calculate the "sample standard deviation" (rather than referring to just one specific number). From this point of view, the "sample standard deviation" becomes a random variable also since it depends on random outcomes.

4. "Standard deviation" can refer to an estimate (like 0.43) of the "population standard deviation" (usually an estimate that is based on a particular sample of data). There are are a variety of ways to make estimates. There is no law that says you can only use the "sample standard deviation" as your estimate of the the "population standard deviation".

5. "Standard deviation" can refer to a formula or algorithm for making an estimate of the "population standard deviation" as a function of the data. This is called an "estimator of the standard deviation" and such an estimator is a random variable since the data is random.

There is no law that says than an estimate or an estimator must use the same formula as the formula for the population standard deviation. In fact, that would be impossible since the formula for the "population standard deviation" uses inputs that are probabilities and a formula for estimating the standard deviation must use inputs that are data values. The data might involve observed frequencies of values, but observed frequencies are not the same as probabilities. (Think of tossing a fair coin an odd number of times. The fraction of heads can't turn out to be 1/2.)

The formula you gave is correct for 1) if the signal and noise are independent random variables.

if you talk about specific numbers from an experiment, your talking about 2) or 4). If you are discussing general statistical concepts, you usually refer to 1), 3) or 5). If you have lots of data, It is likely that the formula you gave is useful for 2),3),4),5) also.

A further complication of your problem is that you have a variable sample rate. If you have a random variable X that varies continuously in time, you probably won't get the same standard deviation ( in any sense of that phrase) if you change sample rates. If you want to talk about "the" standard deviation of the random variable X, you must make an even more specialized definitions of "standard deviation" that doesn't depend on the particular sample rate. The basic idea is that the definition must incorporate the concept of "per unit time". This is why chiro suggests you look at the theory of Brownian motion.

If you use only 1 sample rate in your experiments, then the formula you gave is OK.


text:
# Bowditch rule is also termed as:

This question was previously asked in
SSC JE CE Previous Year Paper 10 (Held on 30 Oct 2020 Evening)
View all SSC JE CE Papers >
1. transit rule
2. axis rule
3. graphical rule
4. compass rule

## Answer (Detailed Solution Below)

Option 4 : compass rule
Free
ST 1: Logical reasoning
5333
20 Questions 20 Marks 20 Mins

## Detailed Solution

Concept:

Balancing of errors: The process of adjusting the latitudes and departures to make the algebraic sum of latitudes or departures to zero is called the balancing of errors.

The two types of balancing rules to eliminate errors in traverse surveying are as follows:

1) Bowditch rule (Compass rule)/Compass rule:

It is most commonly adopted when angular measurement and linear measurement both are nearly of same precision.

The correction is considered directly proportional to the length of the side.

By Bowditch rule Correction to a particular line is given by

$${C_L} = \;l \times \frac{{{\bf{\Sigma }}L}}{{{\bf{\Sigma }}l}}$$

$${C_D} = \;l \times \frac{{{\rm{\Sigma }}D}}{{{\rm{\Sigma }}l}}$$

Where CL, Cis corrections in latitude and longitude for a line.

Correction for Latitude/Departure = Total error in Latitude/Departure ×  $$\frac{{{\bf{length}}\;{\bf{of}}\;{\bf{the}}\;{\bf{side}}}}{{{\bf{perimeter}}\;{\bf{of}}\;{\bf{the}}\;{\bf{traverse}}}}$$

2) Transit rule:

When angular measurements are more precise than linear measurements, the transit method is adopted.

Correction to latitude/departure of any side = Total error in latitude/departure ×  $$\frac{{{\bf{Latitude/Departure}}\;{\bf{of}}\;{\bf{the}}\;{\bf{side}}}}{{{\bf{Arthmetical}}\;{\bf{sum}}\;{\bf{of}}\;{\bf{all}}\;{\bf{latitudes/departure}}}}$$

1. When the adjustment is made by the Bowditch rule, the length of the sides becomes less and the angle becomes more than that when the adjustment is made by the transit rule.

2. In Bowditch rule, it is assumed that the errors in linear measurements are proportional to $$\sqrt l$$ and angular measurements are proportional to $$\frac{1}{{\sqrt l }}$$


text:
# Math Help - sequence problem (more of a limits question)

1. ## [Solved] sequence problem (more of a limits question)

Here' we're asked to determine whether the sequence converges or diverges, and if it converges we are asked to find the limit. We are given the sequence
$a_n = \sqrt[n]{2^{1+3n}}$

So I can see by putting this into my calculator that this is going to converge to 8. My problem is showing this mathematically. Here's where I'm stuck.

$a_n = \sqrt[n]{2^{1+3n}} = \left(2^{1+3n}\right)^{1/n}$

Easy enough, now the tough part....

$\displaystyle \lim_{n \to \infty}\left(2^{1+3n}\right)^{1/n}$

Where do I even begin on this? Do I need to use a natural log or something? Wood that be the thing to do? (terrible pun, but I had to do it.)

I obviously can't say that my exponent is going to 0 as n goes to infinity, because that's just not true. If it were the answer would just be 1 and that'd be it, but that's obviously not the case.

If anyone could help point me in the right direction, that'd just be super.

Thanks!

2. Originally Posted by pirateboy
Here' we're asked to determine whether the sequence converges or diverges, and if it converges we are asked to find the limit. We are given the sequence
$a_n = \sqrt[n]{2^{1+3n}}$

So I can see by putting this into my calculator that this is going to converge to 8. My problem is showing this mathematically. Here's where I'm stuck.

$a_n = \sqrt[n]{2^{1+3n}} = \left(2^{1+3n}\right)^{1/n}$

Easy enough, now the tough part....

$\displaystyle \lim_{n \to \infty}\left(2^{1+3n}\right)^{1/n}$

Where do I even begin on this? Do I need to use a natural log or something? Wood that be the thing to do? (terrible pun, but I had to do it.)

I obviously can't say that my exponent is going to 0 as n goes to infinity, because that's just not true. If it were the answer would just be 1 and that'd be it, but that's obviously not the case.

If anyone could help point me in the right direction, that'd just be super.

Thanks!
use the properties of exponents This gives

$\displaystyle (2^{1+3n})^{\frac{1}{n}}=2^{\frac{1+3n}{n}}=2^{\fr ac{1}{n}+3}=2^{\frac{1}{n}}\cdot 2^{3}=8\cdot 2^{\frac{1}{n}}$

3. Hi pirateboy.
The limit becomes easy if you see
$(2^{1+3n})^{1/n} = e^{ \ln (2^{1/n+3})$
So, by the continuity of e and the properties of ln, the problem becomes to calculate the limit,
$(1/n + 3) \ln (2)$, When [tex] n \rightarrow \infty [\MATH] you get
[tex]3\ln(2) = ln(2^3)[tex]. The initial limit yields $e^ln(2^3) = 2^3= 8$.
Everk

4. Doh! I can't believe I didn't see that!

Everk, I think I see what you're talking about.

5. ## Solved

So to finish it out...

$\displaystyle \lim_{n \to \infty}\sqrt[n]{2^{1+3n}} = \lim_{n \to \infty}\left(2^{1+3n}\right)^{1/n} =\lim_{n \to \infty} 2^{1/n + 3} = 2^{0+3} = 8$

Thanks, guys.


text:
The Spiceworks Community is being updated:
Features may be a tad unstable during this time.

## PowerShell

script to change files in domain users AppData\Roaming folder

I have a spreadsheet with student names with two columns. First column has "lastname, firstname" format of our students. The second column has the student ID for that student. We use AD and need to plug the student ID into their user accounts into the "fax" field. I'm not sure if it is possible to have powershell search the name in AD from the first column of the excel sheet, and then plug in the ID from the second column in the "fax" field of AD.

I hope this makes sense. It seems that it would be possible but "testing" PS scripts on a Domain Controller isn't going to happen.

Mace
OP
##### cduff Apr 23, 2015 at 8:28 UTC
Powershell
$csv = Import-Csv -Path "T:\156\in.csv" ForEach($user in $csv) {$parts = $user."name" -split ","$sam = "$($parts[1].Trim()).$($parts[0].Trim())"

Get-ADUser $sam | Set-ADUser -Fax$user.'student id'
}

If you save the sheet as a csv file, then this is the basics of it.  I've assumed that the column headers are 'name' and 'student id'.

Popular Topics in PowerShell
Spiceworks Help Desk

The help desk software for IT. Free.

Track users' IT needs, easily, and with only the features you need.

## 7 Replies

· · ·
Mace
OP
##### cduff Apr 23, 2015 at 7:27 UTC

What is the format of the samaccountname, because that is probably what you'll want to query from?  Is it possible that two students could have the same last, first? How do you distinguish between them? Or is the value of the last, first column their CN?  If so, are they in the same OU? Need more details.

You'll have to test whatever someone would post here against a DC somewhere anyway.  You'll need to use Set-ADUser and it has a -WhatIf parameter.  You can use that to ensure that no changes are made to the DC until you get everything worked out.

2
· · ·
Habanero
OP
##### John4120 Apr 23, 2015 at 7:28 UTC

I'm not certain about doing it by PowerShell script but I know this can be done with the CSVDE command.

0
· · ·
Serrano
OP
##### Joesyuh Apr 23, 2015 at 7:52 UTC

You may find this script I wrote sort of helpful. I know some people will probably pick it apart as amateurish, and I would agree. I think though that it shows the basic concepts you are looking for:

Powershell
Import-Module ActiveDirectory

#Create Excel Object and prepare variables
$filePath = "[EXCEL FILE PATH]"$sheetName = "[NAME OF SHEET TO USE]"
$objExcel = New-Object -ComObject Excel.Application$objExcel.Visible = $false$WorkBook = $objExcel.Workbooks.Open($filePath)
$WorkSheet =$WorkBook.sheets.item($sheetName) #count the columns and rows$WorksheetRange = $workSheet.UsedRange$RowCount = $WorksheetRange.Rows.Count$ColumnCount = $WorksheetRange.Columns.Count$count = 0

#Loop through excel spreadshet until the last row.
While ($count -lt$RowCount )
{
#Associate Columns with variables
$firstName =$workSheet.Range("C$count").Text$lastName = $workSheet.Range("D$count").text
$san =$firstName + " " + $lastName #Do work Here$count++
}

$objExcel.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
Remove-Variable objExcel
Stop-Process -processname Excel

To Change the columns where the first name and last name are stored just switched the column designation before the $count in these two lines: Powershell $firstName = $workSheet.Range("C$count").Text
$lastName =$workSheet.Range("D$count").text  You could also add your own third variable for Student ID Powershell $studentID = $workSheet.Range("X$count").Text

Then build the SAN and from the SAN assign the Fax number field to the $studentID variable. Probably not much help but I thought I would try! 0 · · · Anaheim OP ##### dale.mathis Apr 23, 2015 at 7:55 UTC I figured there would be more details needed but I didn't know what. The students log in with firstname.lastname. The Excel sheet is in lastname,firstname format. with student logon names, in the event there is dupes, we use firstname.middleinitial.lastname. There are no dupes like this yet though and this would be a one time thing. the excel sheet was not pulled from AD, so the CN's are not present. it was pulled from our student database and it doesn't integrate with AD. I wouldn't "trial and error" on my own. I trust the SW community to supply decent answers. I didn't know about the Whatif param though. 0 · · · Mace OP Best Answer ##### cduff Apr 23, 2015 at 8:28 UTC Powershell $csv = Import-Csv -Path "T:\156\in.csv"

ForEach($user in$csv) {
$parts =$user."name" -split ","
$sam = "$($parts[1].Trim()).$($parts[0].Trim())" Get-ADUser$sam |
}

If you save the sheet as a csv file, then this is the basics of it.  I've assumed that the column headers are 'name' and 'student id'.

1
· · ·
Thai Pepper
OP
##### BloodHoundGang Apr 23, 2015 at 8:41 UTC

You make it look all so easy Craig.

0
· · ·
Thai Pepper
OP
##### bobmccoy Apr 24, 2015 at 1:31 UTC

John4120 wrote:

I'm not certain about doing it by PowerShell script but I know this can be done with the CSVDE command.

This is absolutely doable by PowerShell and is more intuitive and easier to customize AD parameters than using CSVDE.

Additionally, there are dozens of scripts out there in the various repositories that do this, or incredibly close to it.  This is a very common scenario.

0

This discussion has been inactive for over a year.

You may get a better answer to your question by starting a new discussion.

Oops, something's wrong below.


text:
PREPRINT
A41DCEE0-E3CF-4143-86F3-5CC322A5D976

# APPleSOSS: A Producer of ProfiLEs for SOSS. Application to the NIRISS SOSS Mode

Michael Radica, Loïc Albert, Jake Taylor, David Lafrenière, Louis-Philippe Coulombe, Antoine Darveau-Bernier, René Doyon, Neil Cook, Nicolas Cowan, Néstor Espinoza, Doug Johnstone, Lisa Kaltenegger, Caroline Piaulet, Arpita Roy, Geert Jan Talens
arXiv:2207.05136

Submitted on 11 July 2022

## Abstract

The SOSS mode of the NIRISS instrument is poised to be one of the workhorse modes for exoplanet atmosphere observations with the newly launched James Webb Space Telescope. One of the challenges of the SOSS mode, however, is the physical overlap of the first two diffraction orders of the G700XD grism on the detector. Recently, the ATOCA algorithm was developed and implemented as an option in the official JWST pipeline, as a method to extract SOSS spectra by decontaminating the detector -- that is, separating the first and second orders. Here, we present APPleSOSS (A Producer of ProfiLEs for SOSS), which generates the spatial profiles for each diffraction order upon which ATOCA relies. We validate APPleSOSS using simulated SOSS time series observations of WASP-52b, and compare it to ATOCA extractions using two other spatial profiles (a best and worst case scenario on-sky), as well as a simple box extraction performed without taking into account the order contamination. We demonstrate that APPleSOSS traces retain a high degree of fidelity to the true underlying spatial profiles, and therefore yield accurate extracted spectra. We further confirm that the effects of the order contamination for relative measurements (e.g., exoplanet transmission or emission observations) is small -- the transmission spectrum obtained from each of our four tests, including the contaminated box extraction, deviates by $\lesssim$0.1$\sigma$ from the atmosphere model input into our noiseless simulations. We further confirm via a retrieval analysis that the atmosphere parameters (metallicity and C/O) obtained from each transmission spectrum are consistent at the 1$\sigma$ level with the true underlying values.

## Preprint

Comment: 12 pages, 9 figures. Submitted to PASP

Subjects: Astrophysics - Instrumentation and Methods for Astrophysics; Astrophysics - Earth and Planetary Astrophysics


text:
## Hide n Seek

View as PDF

Points: 12 (partial)
Time limit: 2.5s
Memory limit: 32M

Authors:
Problem types

Now that Griffy has made lots of friends, he would like to play a game with them! Hide and seek is a game where the seeker needs to find and tag stationary hiders, all around the school. Griffy volunteered to be the seeker first, so he can show off his super-sonic flying speed! The school is rows by columns, walls are represented by Xs, empty space is represented by .s, Griffy's starting position will be G, and the locations of the hiders are represented by H. Griffy can fly one square up, down, left, or right of his current position in 1 second, and cannot fly through walls.

This, of course, is a great opportunity for you to hone your programming skills. Please determine the minimum amount of time it will take for Griffy to find all his hiding friends!

Note: It is guaranteed that a valid path exists.

#### Input Specification

First line: , , , space separated .

Next lines: characters per line, representing the school map.

#### Output Specification

Output one integer, the minimum time in seconds that Griffy will take to find all the hiders. It is guaranteed that Griffy can find all hiders.

#### Sample Input

3 5 2
..H..
..X.H
G...X

#### Sample Output

7

#### Explanation for Sample Output

The path that takes the least amount of time is 2 up, 4 right and 1 down, for a total of seconds.

• commented on Sept. 7, 2020, 11:12 p.m.

Can someone give me a hint as to why I get WA after the fifth test case.

• commented on June 23, 2019, 7:49 p.m.

Is a greedy algorithm where you choose the nearest hider each time insufficient?

• commented on Oct. 26, 2019, 2:03 p.m.

Imagine linear time TSP lmao.

• commented on July 17, 2016, 12:00 p.m. edited

This comment is hidden due to too much negative feedback. Click here to view it.

• commented on May 22, 2015, 10:31 p.m.

Could anyone give me a hint as to why my program RTE's after the fifth test case.

Thanks!

• commented on Jan. 17, 2015, 1:47 p.m.

Recursion isn't needed (this from a person who hasn't solved it yet).

• commented on Jan. 17, 2015, 2:31 p.m.

There are many ways to solve a problem. The problem types list a few common ways; not all of them may be required.

• commented on Jan. 17, 2015, 1:50 p.m.

Oh never mind. I'm dumb.


text:
# What is global Lorentz transformation and what is local Lorentz transformation?

I will consider $$\textbf{spacetime}$$ as $$(M,\eta)$$ where $$M$$ is a four dimensional $$\textbf{manifold}$$ and $$\eta$$ the metric which in this coordinates \begin{align*} x \colon M &\longrightarrow \mathbb{R}^4\\ p &\mapsto x(p)=(x_0,x_1,x_2,x_3). \end{align*} is given by $$\eta=dx^0\otimes dx^0-dx^1\otimes dx^2-dx^2\otimes dx^1-dx^3\otimes dx^3 \tag1$$

An $$\textbf{observer}$$ is a worldline $$\gamma$$ with together with a choice of basis $$O=v_{\gamma,\gamma(\lambda)} \equiv e_0(\lambda) , e_1(\lambda), e_2(\lambda), e_3(\lambda)$$ of each $$T_{\gamma(\lambda)}M$$ where the observer worldline passes, if $$\eta(e_a(\lambda), e_b(\lambda)) = \eta_{ab} = \left[ \begin{matrix} 1 & & & \\ & -1 & & \\ & & -1 & \\ & & & -1 \end{matrix} \right]_{ab} \tag2$$

$$v_{\gamma,\gamma(\lambda)}$$ is the tangent vector of the the curve $$\gamma$$ at the point $$\gamma(\lambda)$$

In text books i've found three definition of $$\textbf{Lorentz transformation} \quad \Lambda$$

1. $$\Lambda \colon \mathbb{R}^4 \longrightarrow \mathbb{R}^4$$ is a group of coordinate transformations that leave eq.1 in the same form ,that is $$\Lambda \cdot x(p)=y(p)=(y_0,y_1,y_2,y_3)$$ such that in this coordinate $$\eta=dy^0\otimes dy^0-dy^1\otimes dy^2-dy^2\otimes dy^1-dy^3\otimes dy^3$$
2. $$\Lambda \colon M \longrightarrow M$$ a Spacetime diffeomorphism such that $$\Lambda_* \eta=\eta$$ where $$\Lambda_* \eta$$ is the pullback of the metric $$\eta$$
3. $$\Lambda \colon T_pM \longrightarrow T_pM$$ such that $$\Lambda O=O'=e'_0(\lambda) , e'_1(\lambda), e'_2(\lambda), e'_3(\lambda)$$ satisfy the eq.2 that is $$\eta(e'_a(\lambda), e'_b(\lambda)) = \eta_{ab} = \left[ \begin{matrix} 1 & & & \\ & -1 & & \\ & & -1 & \\ & & & -1 \end{matrix} \right]_{ab}$$

My question is which is of these transformation is global Lorentz transformation and which is local?

• Minor question: What's with the off-diagonal terms $dx^1\otimes dx^2$, $dy^1\otimes dy^2$, etc? – Qmechanic Apr 15 '20 at 20:13

The three definitions are the same. They are ways of saying the same thing. Since you have a manifold $$(M,\eta)$$ this is a flat, Minkowski, spacetime. The Lorentz transformation is global on Minkowski spacetime.

In a curved spacetime the metric is usually denoted $$g$$, rather than $$\eta$$. $$g$$ is, in general, a function of time and position. At each point there is a Minkowski tangent space, meaning that the manifold is locally Minkowski (to the accuracy of measurement) and that local Lorentz transformations can be applied within a neighbourhood of each point.

• They are not the same. Suppose we are measuring the spin of a particle.1 Means just change of coordinates and since coordinates does no matter in physics we could choose say polar coordinates and the physics would be the same in other words 1 is imagination of our mind ... – amilton moreira Apr 15 '20 at 19:17
• 2. Is something that is happen in the real world that is we are rotating the observer and the spinor. I does not have a consequence in physics because it is a symmetry of the metric .... – amilton moreira Apr 15 '20 at 19:22
• 3. Is a rotation of the observer (the apparatus) in this case the spinor get a fase – amilton moreira Apr 15 '20 at 19:23
• There are no spinors here, and you have chosen Minkowski coordinates given by $\eta$. You already specified them, they cannot be polar. – Charles Francis Apr 15 '20 at 19:46
• I choosed the coordinates just to specify the metric and to define lorentz transformation as most books do . I did not say that the problem would be in this coordinates – amilton moreira Apr 15 '20 at 20:05

The basic definition of the Lorentz transformation is, given a vector space $$V$$ equipped with a Minkowski metric $$\eta$$, it is the group that leaves the norm invariant (in other words, definition 1).

In a spacetime, every tangent space can be considered as a copy of Minkowski space, ie for every $$p \in M$$, $$T_p M \cong V$$, since by Sylvester's law, we can always put the metric tensor $$g_p$$ at that point in the appropriate form by a change of basis (that basis being an orthonormal basis $$\{ e_\mu \}$$). Then at each point, you can perform a Lorentz transform of that basis.

Diffeomorphisms on a manifold are a rather large class, but there exists a subset of diffeomorphisms such that, if $$\phi \in \mathrm{Diff}(M)$$, the pushforward on a vector at $$p$$, $$\phi^* v$$, corresponds to a Lorentz transform. Just by having say

$$$$\frac{\partial x^\mu(p)}{\partial y^\nu(p)} \in \mathrm{SO}(3,1)$$$$

Locally, in the Riemann/Fermi coordinates, this is roughly equivalent to a Lorentz transform, since the normal neighbourhood is diffeomorphic to $$T_pM$$.


text:
# 5.14: Conservation Laws

Name: _________________________________________

Date: _______________________

Partners:____________________________________________________________

Equipment

 LabPro InterfaceTwo motion detectorsForce sensorForce software file Dynamics trackDynamics cartPulleyHanging masses

Introduction

Newton’s Second Law directly relates the net force acting on an object to its acceleration. However, the force acting on an object can also be related to the other kinematic parameters of the system (the time, position, velocity, and changes in these variables). The Work-Energy and Impulse-Momentum relations directly relate force to these other parameters. More importantly, in closed systems, these relations generalize to the Laws of Energy and Momentum Conservation. These fundamental laws of physics provide an alternative to Newton’s Laws for the study of motion.

I. An Alternative to Newton’s Laws

Open the file Force.

Set the sensor to the ±10 N setting and securely attach it to the top of the cart.

Measure the mass of your cart and sensor. Record it below.

mass of cart and sensor, m =  ____________  kg

Select Experiment/Calibrate and select the Force sensor. Select Calibrate Now. You will now perform a two-point calibration of the force sensor:

• For the first calibration point, do not apply any force to the sensor, enter 0 N, and hit Keep.
• For the second calibration point, attach a 200 g mass to the sensor by means of a string passing over the pulley. Enter the weight of this mass (1.96 N) and hit Keep.

You are going to repeat the same series of experiments you conducted while exploring Newton’s Laws. However, rather than focusing on the relationship between force and acceleration, you will focus of the interrelationships between force and the other kinematic variables.

Attach 200 g to the sensor via a string passing over the pulley. Hold the cart in place about 20 cm in front of the motion detector, press Collect, and then release the cart. Make sure that the track is clean, the wheels of the cart turn freely, and the force sensor cord does not drag behind the cart. The resulting graphs of force and acceleration vs. time should look familiar.

To see a graph of momentum vs. time, you have to “teach” the program how to calculate momentum. To do this,

• Select Data/New Calculated Column and enter the appropriate name and units for a momentum column.
• In the equation box, enter the appropriate equation to calculate momentum. (You do not need to enter an equal sign in your equation.) Use the Variables pull-down menu to select the appropriate variable in your equation. Press Done.
• Replace the graph of acceleration vs. time with a graph of momentum vs. time.

Select the same large region of “good” data on both graphs and complete the first row of the table below. Directly measure the initial and final momentum from your momentum vs. time graph and determine the impulse acting on the cart during this time interval by determining the area under the force vs. time graph. Although the software does not automatically calculate an uncertainty for these measurements, this does not mean that the data is exact. Estimate and record an uncertainty for each measurement.

To see a graph of kinetic energy, you have to “teach” the program how to calculate kinetic energy. To do this,

• Select Data/New Calculated Column and enter the appropriate name and units for a kinetic energy column.
• In the equation box, enter the appropriate equation to calculate kinetic energy.
• Since work as the product of the force applied to the cart and the displacement of the cart, change the force vs. time graph to a force vs. position graph and replace the lower graph with a kinetic energy vs. position graph.

Select a large region of “good” data on both graphs and complete the first row of the second table below.

 Hanging Mass (g) Pfinal (kg m/s) Pinitial (kg m/s) P (kg m/s) Impulse (N s) 200 ± ± 150 ± ± 100 ± ± 50 ± ±
 Hanging Mass (g) KEfinal (kg m2/s2) KEinitial (kg m2/s2) KE (kg m2/s2) Work (N m) 200 ± ± 150 ± ± 100 ± ± 50 ± ±

Complete both of the above tables.

Question: Describe and defend your method for estimating the uncertainties in your data.

Question: Is there a relationship, within measured uncertainties, between impulse and change in momentum?

Question: Is friction small enough to be reasonably ignored? Would including friction make the agreement between your data and the impulse-momentum relation better or worse? Explain.

Question: Is there a relationship, within measured uncertainties, between work and change in kinetic energy?

Question: Is friction small enough to be reasonably ignored? Would including friction make the agreement between your data and the work-energy relation better or worse? Explain.

II. Collisions

Remove the force sensor from the interface and connect a second motion detector. Place the motion detectors at opposite ends of the track. Configure LoggerPro to display a single graph of both velocities.

Since “away” is considered the positive direction for a motion detector, the two motion detectors have conflicting coordinate systems. To fix this problem, select Experiment/Set Up Sensors/Show All Interfaces. Right-click one of your motion detectors and select Reverse Direction. Now both motion detectors will refer to the same direction as positive.

A. Velcro-Velcro Collisions

Arrange your two carts such that when they collide they will stick together.

Roll cart 1 in the positive direction, colliding with a stationary cart 2. Roll cart 1 fast enough so that after the collision the two carts roll to the end of the track, but slow enough so that the carts don’t “jump” slightly off the track on contact.

1. Tracking Momentum during a Collision

Measure the mass of each cart and record it below.

mass of cart 1, mcart 1 =  ____________  kg

mass of cart 2, mcart 2 =  ____________  kg

To visualize how momentum behaves during the collision,

• Create a data table with columns for Momentum1, Momentum2, and Total Momentum using Data/New Calculated Column and entering the appropriate name and units. In the equation box, enter the appropriate equation to calculate each momentum.
• Create a single full-screen graph of Momentum1, Momentum2, and Total Momentum vs. time.

Question: Is the momentum of cart 1 conserved (i.e. constant) during the collision? If not, does it gain or lose momentum? Explain.

Question: Is the momentum of cart 2 conserved during the collision? If not, does it gain or lose momentum? Explain.

Question: Is the total momentum in the system of the two carts conserved during the collision? Should it be? Explain.

2. Tracking Kinetic Energy during a Collision

To examine the same collision in terms of kinetic energy, rather than momentum, LoggerPro can also be “taught” how to measure kinetic energy.

Using the technique described above, create calculated columns for Kinetic Energy1, Kinetic Energy2, and Total Kinetic Energy. Create a single full-screen graph of Kinetic Energy1, Kinetic Energy2, and Total Kinetic Energy vs. time.

Question: Is the kinetic of cart 1 conserved (i.e. constant) during the collision? If not, does it gain or lose kinetic energy? Explain.

Question: Is the kinetic energy of cart 2 conserved during the collision? If not, does it gain or lose kinetic energy? Explain.

Question: Is the total kinetic energy in the system of the two carts conserved during the collision? Should it be? Explain.

Question: If the total kinetic energy in the system of the two carts decreased during the collision, where did this energy go?

Add a second graph to your display. Make the top graph Momentum1, Momentum2, and Total Momentum vs. time and the bottom graph Kinetic Energy1, Kinetic Energy2, and Total Kinetic Energy vs. time. Adjust the scales on your graphs so that they are easy to read. Print this page and attach it to the end of the activity. Note that your graph may look better in landscape mode.

3. Other Types of Collisions

Imagine different types of collisions. For example, what if cart 1 was twice as massive (i.e. carrying a 500 g black bar)? What if cart 2 was moving and cart 1 stationary? What if both carts were moving? Would momentum and kinetic energy behave the same way they did in the simple collision just studied?

For the following three collisions, add a 500 g black bar to cart 1 (and alter your LoggerPro equation for Momentum 1 and Kinetic Energy 1):

• Cart 1 colliding with a stationary cart 2.
• Cart 2 colliding with a stationary cart 1.
• Cart 1 and cart 2 in a head-on collision.

For each collision, prepare and print the momentum and kinetic energy graphs described above and attach them to the end of the activity. Below each graph, clearly describe the collision and your findings regarding momentum and kinetic energy conservation for that collision.

Question: What conclusion(s) can you draw about the amount of momentum present before and after each collision? Do all 4 collisions (including the one analyzed in the previous section) support the same conclusion?

Question: What conclusion(s) can you draw about the amount of kinetic energy present before and after each collision? Do all 4 collisions support the same conclusion?

B. Magnet-Magnet Collisions

Arrange your two carts such that they repel each other when they get close together.

Roll cart 1 in the positive direction, colliding with a stationary cart 2. Roll cart 1 fast enough so that after the collision cart 2 rolls to the end of the track, but slow enough so that the carts don’t actually touch during the interaction.

Prepare, print, and attach this graph to the end of the activity.

Question: Is the total momentum in the system of the two carts approximately constant during the collision? Should it be? Explain.

Question: Is the total kinetic energy in the system of the two carts approximately constant during the collision? Should it be? Explain.

Question: If the total kinetic energy in the system of the two carts decreased during the collision, did it decrease by a smaller amount than in the velcro-velcro collision?

Repeat the remaining two collisions you analyzed earlier, except using the magnet-magnet interaction.

• Cart 2 colliding with a stationary cart 1.
• Cart 1 and cart 2 in a head-on collision.

For each collision, prepare and print the momentum and kinetic energy graphs described above and attach them to the end of the activity. Below each graph, clearly describe the collision and your findings regarding momentum and kinetic energy conservation for that collision.

Question: What conclusion(s) can you draw about the amount of momentum present before and after each collision? Do all 3 collisions support the same conclusion? Compare these conclusions to the conclusions drawn from the velcro-velcro data.

Question: What conclusion(s) can you draw about the amount of kinetic energy present before and after each collision? Do all 3 collisions support the same conclusion? Compare these conclusions to the conclusions drawn from the velcro-velcro data.


text:
# Pointers and scope with recursion

## Recommended Posts

zoner7    110
Alright. I have a binary tree here, and I was asked to delete all the leaves in the tree. The following code works, but I'm not positive why. Suppose I am at one a leaf that has no left or right nodes. I want to delete this node. I am going to learn that this leaf has no children after the following two calls are made. recursive_clear(sub_root->left); //clear lefthand subtree of node recursive_clear(sub_root->right);//clear the righthand subtree of that node. The only issue here is that the sub_root is set to NULL when these functions are called. Since sub_root is a pointer, when one of these functions returns, shouldn't sub_root still point to NULL? Clearly this isn't the case. If The pointer didn't change its value after leaving a function, then I would never be able to progress up the tree after reaching the bottom. I just always thought that pointers kept their values after going out of scope... or is it only the dynamic memory that the pointer points to that doesn't go out of scope. The code of the whole function is below. Thank you in advance!
template <class Entry>
void Binary_tree<Entry> :: clear( )
/* Post: All entries of the binary tree are removed. */
{
recursive_clear(root);
return;
} //clear

template <class Entry>
void Binary_tree<Entry> :: recursive_clear(Binary_node<Entry> * &sub_root)
/* Post: The subtree rooted at sub_root is cleared. */
{
Binary_node<Entry> *temp;
if (sub_root != NULL)
{
temp = sub_root;
recursive_clear(sub_root->left); //clear lefthand subtree of node
recursive_clear(sub_root->right);//clear the righthand subtree of that node.
sub_root = NULL;
delete temp;
}
return;
} //recursive_clear

##### Share on other sites
Captain P    1092
You're passing references to pointers here, so if you set that pointer to NULL inside the function, you're setting the actual pointer to NULL, not a local copy of it. However, sub_root is referring to a different pointer in each recursive_clear() call.

So, if we have a binary tree of 3 nodes, a root with only two child-nodes, then calling recursive_clear on root results in the following:
- recursive_clear(root)   - recursive_clear(root->left)      - recursive_clear(NULL)      - recursive_clear(NULL)   // here, root->left is set to NULL   - recursive_clear(root->right)      - recursive_clear(NULL)      - recursive_clear(NULL)   // here, root->right is set to NULL// here, root is set to NULL
In all cases, the function receives a different pointer, and although that pointer reference is always named sub_root, it is never referring to the same pointer.

Now, it's not necessary to set all those pointers to NULL, considering that you're deleting the node that contains these pointers immediately thereafter anyway. You only need to do that for the root pointer. There's no need for a temp pointer either: just call delete on sub_root and then set it to NULL.

##### Share on other sites
zoner7    110
suppose that I had a function that is passed a pointer from main

int main(){int *p = new int;*p = 5;int *q = new int;*q = 10;int *d;foo (p);return 0;}void foo (int *p, int *q, int *d){*p = 10; //so now the integer p points to 5, and this will remain true after scope returns to main. right?delete q; //Now the dynamic memory q pointed to remains deleted after the function ends.q = &d;   //here p becomes a pointer to q. Will p continue to point to q after control returns to main?  //This is definitely the case when we are working with class members, but will this situation work similarly?}How would passing the address of a pointer work differently?  I'm still a little confused on that point.Thank you

##### Share on other sites
Quote:
 Original post by zoner7suppose that I had a function that is passed a pointer from main*** Source Snippet Removed ***

1. you need to rewrite your comments so they actually make sense, so I apologize if my reply makes no sense.

2. passing an address of a pointer is essentially passing the address of an address, which usually doesn't make much sense for a multitude of reasons. I remember someone else saying this in some other thread, but it's like sending someone a link to a website or sending someone a link to a link to a website.

You want to be messing with the website, and your program is trying to mess with links to the website. kind of.

##### Share on other sites
Captain P    1092
First of all, let's stop using the same variable names. It only seems to confuse you. Now, here's your code, with explanations on what's going on:

int main(){	int *a = new int;	// Let's call this new int 'intA'	*a = 5;		int *b = new int;	// Let's call this new int 'intB'	*b = 10;		int *c;	// You forgot to initialize c! It now contains a random address.		foo (a, b, c);	// Now, 'intB' no longer exists, but b still holds the address of what once was 'intB'.	// Pointer aliasing - multiple pointers pointing to the same object - can be a dangerous thing!	// a still points to 'intA', which has a value of 10. c still points to the same old random address.		return 0;	// You forgot to delete 'intA'!}void foo (int *p, int *q, int *r){	// p, q and r are copies of a, b and c. They have the same values, so p and a are pointing to 'intA',	// q and b are pointing to 'intB' and r and c both contain the same random address.	// Changes made to p, q and r themselves have no effect on a, b and c: they may have the same value,	// but they certainly aren't the same pointers. Changes made to 'intA' and 'intB' will, of course,	// be 'visible' outside this function.		*p = 10;	// this changes 'intA's value to 10.		delete q;	// This deletes 'intB'.		q = &r;	// q now points to what r is pointing at: a random address. c, q and r now have the same value.}

Quote:
 Original post by way2lazy2care2. passing an address of a pointer is essentially passing the address of an address, which usually doesn't make much sense for a multitude of reasons. I remember someone else saying this in some other thread, but it's like sending someone a link to a website or sending someone a link to a link to a website

There are no pointer-to-pointers being passed around in that function, just pointers.

##### Share on other sites
Quote:
 Original post by Captain PThere are no pointer-to-pointers being passed around in that function, just pointers.

I was replying to "How would passing the address of a pointer work differently? I'm still a little confused on that point," at the end of his source snippet.

##### Share on other sites
Captain P    1092
Ah, you're right, I missed that part. Quote tags strip away code and that line was still inside the source tags. I agree, in C++, you shouldn't be working with pointers to pointers in most cases.

Either way, the same rules apply. The value of these pointer-to-pointers (the address of a pointer) is copied into local pointer-to-pointers. You may want to read up on 'passing by value' and 'passing by reference'. Passing by value provides a function with the value of an object, not with the original object itself. Passing by reference gives the function access to the original object. Note: although pointers are conceptually similar to references, they're not the same.