text:
The Method of Annihilators Examples 1

# The Method of Annihilators Examples 1

On The Method of Annihilators page, we looked at an alternative way to solve higher order nonhomogeneous differential equations with constant coefficients apart from the method of undetermined coefficients. Consider a differential equation of the form:

(1)
\begin{align} \quad L(D)(y) = g(t) \end{align}

The procedure for solving this differential equation was straightforward. Like always, we first solved the corresponding homogeneous differential equation. We then rewrote the differential equation in terms of differential operators, and determined a differential operator $M(D)$ which annihilated $g(t)$, that is, $M(D)(g(t)) = 0$. We then apply this annihilator to both sides of the differential equation to get:

(2)

The result is a new differential equation that is now homogeneous. In solving this differential equation - we obtain a general solution for which we throw away terms that are linear combinations of the solution to the original corresponding homogeneous differential equation. We then have obtained a form for the particular solution $Y(t)$. We then differentiate $Y(t)$ as many times as necessary and plug it into the original differential equation and solve for the coefficients.

Lastly, as usual, we obtain the general solution to our higher order differential equation as:

(3)
\begin{align} \quad y(t) = y_h(t) + Y(t) \end{align}

We will now look at an example of applying the method of annihilators to a higher order differential equation.

## Example 1

Solve the differential equation $\frac{\partial^4 y}{\partial t^4} - 2 \frac{\partial^2 y}{\partial t} + y = e^t + \sin t$ using the method of annihilators.

The corresponding homogeneous differential equation is $\frac{\partial^4 y}{\partial t^4} - 2 \frac{\partial^2 y}{\partial t} + y$ and the characteristic equation is $r^4 - 2r^2 + 1 = (r^2 - 1)^2 = (r + 1)^2(r - 1)^2 = 0$. Therefore the characteristic equation has two distinct roots $r_1 = 1$ and $r_2 = -1$ - each with multiplicity $2$, and so the general solution to the corresponding homogeneous differential equation is:

(4)
\begin{align} \quad y_h(t) = Ae^{t} + Bte^{t} + Ce^{-t} + Dte^{-t} \end{align}

We now rewrite our differential equation in terms of differential operators as:

(5)
\begin{align} \quad (D + 1)^2(D - 1)^2(y) = e^t + \sin t \end{align}

The differential operator $(D - 1)$ annihilates $e^t$ since $(D - 1)(e^t) = D(e^t) - e^t = e^t - e^t = 0$. The differential operator $(D^2 + 1)$ annihilates $\sin t$ since $(D^2 + 1)(\sin t) = D^2(\sin t) + \sin t = -\sin t + \sin t = 0$. Applying the operator $(D^2 + 1)(D - 1)$ to both sides of the differential equation above gives us:

(6)
\begin{align} \quad (D + 1)^2(D - 1)^2(y) = e^t + \sin t \\ \quad (D^2 + 1)(D + 1)^2(D - 1)^3 (y) = (D^2 + 1)(D - 1)(e^t + \sin t) \\ \quad (D^2 + 1)(D + 1)^2(D - 1)^3 (y) = 0 \end{align}

The roots to the characteristic polynomial of the differential equation above are $r_1 = i$, $r_2 = -i$, $r_3 = -1$ (with multiplicity $2$), $r_4 = 1$ (with multiplicity $3$), and so the general solution to the differential equation above is:

(7)
\begin{align} \quad Y(t) = P \sin t + Q \cos t + Re^{-t} + Ste^{-t} + Ue^{t} + Vte^{t} + Wt^2e^{t} \end{align}

The terms $Re^{-t}$, $Ste^{-t}$, $Ue^{t}$, and $Vte^{t}$ are all contained in the linear combination of the corresponding homogeneous differential from the beginning of this example. Therefore, we discard them to get:

(8)
\begin{align} \quad Y(t) = P \sin t + Q \cos t + Wt^2 e^t \end{align}

We now need to differentiate $Y(t)$ four times to get:

(9)
\begin{align} \quad Y'(t) = P \cos t - Q \sin t + W(2t + t^2)e^t \end{align}
(10)
\begin{align} \quad Y''(t) = -P \sin t - Q \cos t + W(2 + 4t + t^2)e^t \end{align}
(11)
\begin{align} \quad Y'''(t) = -P \cos t + Q \sin t + W(6 + 6t + t^2)e^t \end{align}
(12)
\begin{align} \quad Y^{(4)} = P \sin t + Q \cos t + W(12 + 8t + t^2)e^t \end{align}

Plugging this into the original differential equation gives us:

(13)
\begin{align} \quad \quad \frac{\partial^4 y}{\partial t^4} - 2 \frac{\partial^2 y}{\partial t} + y = e^t + \sin t \\ \quad \quad \left [ P \sin t + Q \cos t + W(12 + 8t + t^2)e^t \right ] - 2 \left [ -P \sin t - Q \cos t + W(2 + 4t + t^2)e^t \right ] + \left [ P \sin t + Q \cos t + Wt^2 e^t \right ] = e^t + \sin t \\ \quad \quad \left ( P + 2P + P \right ) \sin t + \left ( Q + 2Q + Q \right ) \cos t + \left (12W - 4W \right ) e^t + \left (8W - 8W \right )te^t + \left ( W - 2W + W \right ) t^2 e^t = e^t + \sin t \\ \quad 4P \sin t + 4Q \cos t + 8W e^t = e^t + \sin t \end{align}

From the equation above, we see that $P = \frac{1}{4}$, $Q = 0$, and $W = \frac{1}{8}$. Therefore a particular solution to our differential equation is:

(14)
\begin{align} \quad Y(t) = \frac{1}{4} \sin t + \frac{1}{8}t^2 e^t \end{align}

The general solution to our original differential equation is therefore:

(15)
\begin{align} \quad y(t) = y_h(t) + Y(t) \\ \quad y(t) = Ae^{t} + Bte^{t} + Ce^{-t} + Dte^{-t} + \frac{1}{4} \sin t + \frac{1}{8}t^2 e^t \end{align}


text:
# When is it better to use coupled-cluster (CC) over configuration interaction (CI) calculations?

My experience with different theoretical methods in computational chemistry primarily comes from use and reading papers. My experience is that people almost always use CCSD instead of CISD if they wish to do calculations with single and double excitations.

My understanding is that truncated CI expansions suffer from not being size-extensive and also do not converge very quickly. I do not think coupled-cluster theories suffer in the same way.

Why, however, do people seem to prefer CCSD over CISD? What are the big advantages it has? Is any of it just a habit because CCSD(T) is the preferred method when possible, and so it's easier to make comparisons if these calculations come around in the future and can't be done in some current study?

Also, are there any systems for which it would definitely make more sense to choose a truncated configuration interaction calculation over a coupled-cluster method? Probably systems with some kind of low-lying excited state I would guess...

I'm not looking for a huge amount of math here, although that's totally fine. I would just be fine with the facts and any useful references.

• Personally, I'd always prefer CC before CI... Good thing in CC2 (and other CC response models) for example is that you have a lucky error cancellation in the ground state and excited state dynamical correlation contributions (That's why F12 is so horrible for excited states, it eliminates the error cancellation because it only corrects the ground state contribution btw) which leads to mostly rather good excitation energies. And yes, due to the exponential ansatz CC is size extensive which truncated CI is not. – Fl.pf. Jul 3 '17 at 7:17
• so, I thought about it a little bit more. I couldn't find/think of a case where the CISD excitation energies would be better suited than the CCSD energies. The "advantage" you ask for is probably just that CC exc. are generally better than CISD ones... – Fl.pf. Jul 3 '17 at 11:15
• The main drawback of CC is not being variational (and maybe computational scaling). But since CC is usually more accurate, one does not really care. Or is there any property that benefits from a variational approach? – Feodoran Jul 3 '17 at 16:20

CCSD is preferred in nearly all cases because size-extensivity/size-consistency is a critical property to have for practical chemistry, and on top of that, more of the correlation energy (the part of the energy missing from Hartree-Fock) is captured by CCSD. CISD only accounts correlation energy for up to double excitations and not at all for higher excitations. CCSD accounts for correlation up to double excitations and then approximates all higher excitations as combinations of the single and double excitations it has already calculated. This gives much more accurate numbers for pretty much all systems and provides for size-extensivity/size-consistency. The only time you would really be better off doing CISD than CCSD is if you wanted to do full CI on a 2-electron system, in which case CCSD is not as efficient.

So in short, CCSD is preferred because it almost always gives better, more usable numbers than CISD for similar or better costs (they both scale as ~$n^6$).

format: plain


text:
# drawing arrows on curves and shading regions in TikZ

I need to draw the following figure in my latex using TikZ. I did the following:

\begin{tikzpicture}
\draw (-2,0) -- (2,0);
\draw (0,-2) -- (0,2);
\draw (0,0) circle (1cm);
\draw (1,-.3) node[right] {(2,0)};
\draw (-1,-.3) node[left] {(-2,0)};

\end{tikzpicture}

But how can I shade the upper semi-circle and how can I draw the arrows in between?

Additional Question Thank you so much for your answer. But I have one more doubt: If I use these command in my question I get the diagram right aligned and above the question. But I need it to be beside the question. And sometimes I need to define exactly where I want it to be. What should I do for this?

\question Evaluate $\displaystyle\iint_R dxdy,$ where $R$ is the shaded region in the figure.
\begin{tikzpicture}
\draw (-2,0) -- (2,0);
\draw (0,-2) -- (0,2);
\draw (0,0) circle (1cm);
\draw (1,-.3) node[right] {(2,0)};
\draw (-1,-.3) node[left] {(-2,0)};
\draw[pattern=north west lines] (-1,0) --(1,0) arc[start angle=0, end angle=180, radius=1cm];
\end{tikzpicture}

• Some body give me the solution for the second question. – David Oct 12 '14 at 14:55
• Andd suppose i have two different curves and i need to shade the area between the curve how can i do.. – David Oct 12 '14 at 14:56
• We appreciate one question per post. If you have another question please post a new one. However, for your first question see my previous comment under my answer. As for second question, what are the two curves? Please add some (full) code. – user11232 Oct 12 '14 at 15:01
• $y=x^2$ and $x=y^2$@HarishKumar – David Oct 12 '14 at 15:16

Perhaps there is a better way, but here is one brute force way. You need to load the tikzlibraries patterns and arrows.meta in your preamble.

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{patterns, arrows.meta}
\begin{document}
\begin{tikzpicture}
\draw (-2,0) -- (2,0);
\draw (0,-2) -- (0,2);
\draw (0,0) circle (1cm);
\draw (1,-.3) node[right] {(2,0)};
\draw (-1,-.3) node[left] {(-2,0)};
\draw[pattern=north west lines] (0,-1) --(0,1) arc[start angle=90, end angle=-90, radius=1cm];
\draw[-{To[length=5pt,width=10pt]}] (0,-1) arc[start angle=-90, end angle=-45, radius=1cm];
\draw[-{To[length=5pt,width=10pt]}] (0,1)  arc[start angle=90, end angle=135, radius=1cm];

\end{tikzpicture}
\end{document}

• Kindly revisit my question. I Have onemore doubt. Thank you for ur help...@darthbith – David Oct 12 '14 at 14:42
• If i use these command it is giving this error. {I can't find file 'tikzlibraryarrows.meta.code.tex} give me a solution please. @darthbith – David Oct 12 '14 at 14:48
• @David Two things: 1. If you have a new question, please ask a new question instead of asking your new question within this question. 2. You should use the line \usetikzlibrary{arrows.meta}. It seems like you are trying to use \usetikzlibrary{tikzlibraryarrows.meta} which is incorrect – darthbith Oct 12 '14 at 14:59
• sure...@darthbith – David Oct 12 '14 at 15:01

This uses decorations and \clip.

\documentclass[tikz]{standalone}
\usetikzlibrary{patterns,decorations.markings}
\begin{document}
\begin{tikzpicture}[arrowmark/.style 2 args={decoration={markings,mark=at position #1 with \arrow{#2}}}]
\draw (-2,0) -- (2,0);
\draw (0,-2) -- (0,2);
\begin{scope}
\clip (0,-1) rectangle (1,1);
\draw[draw=none,pattern=north west lines,pattern color=black!50](0,0)
circle(1cm);
\end{scope}
\draw[postaction={decorate},arrowmark={.375}{>},arrowmark={.875}{>}
]  (0,0) circle (1cm);
\draw (1,-.3) node[right] {(2,0)};
\draw (-1,-.3) node[left] {(-2,0)};
\end{tikzpicture}
\end{document}

• Kindly revisit my question. I Have onemore doubt. Thank you for ur help...@Harish – David Oct 12 '14 at 14:43
• @David Add baseline={(current bounding box.center)} to tikzpicture options like \begin{tikzpicture}[baseline={(current bounding box.center)}...] – user11232 Oct 12 '14 at 14:57

Just 4 fun with PSTricks.

\documentclass[pstricks,border=12pt,12pt]{standalone}
\begin{document}
\begin{pspicture}(-5,-5)(5,5)
\pswedge[fillstyle=vlines,hatchcolor=gray]{3}{-90}{90}
\psline(0,-5)(0,5)
\psline(-5,0)(5,0)
\psset{arrows=->,arrowscale=2}
\psarc(0,0){3}{-46}{135}
\psarc(0,0){3}{134}{-45}
\uput[-90](4,0){$(2,0)$}
\uput[-90](-4,0){$(-2,0)$}
\end{pspicture}
\end{document}


text:
# MVC application class

Please could you review and critic my code and logic? Is this is along the right lines of an MVC application class or not?

namespace dh_mvc2;

use dh_mvc2\dispatchers\Base_Dispatcher;
use dh_mvc2\routers\Base_Router;
use dh_mvc2\classes\Config;

class Application {
protected $_config; protected$_autoloader;
protected $_app_path; protected$_framework_path;
protected $_router; protected$_dispatcher;

/**
*
* @param string $app_path * "path/to/application/directory"; * @throws \DH_MVC2_Application_Exeption */ public function __construct($app_path, $run = TRUE) { if (! is_dir ($app_path )) {
require_once 'exeptions/DH_MVC2_Application_Exeption.php';
throw new \DH_MVC2_Application_Exeption ( "Must supply a path to an application directory" );
}

$this->_framework_path = realpath ( dirname ( __DIR__ ) );$this->_app_path = $app_path;$this->set_ini_default_paths ();
$this->init (); if ($run) {
$this->run (); } } /** * add the framework dir and application dir to include path */ private function set_ini_default_paths() {$paths = explode ( PATH_SEPARATOR, get_include_path () );
if (array_search ( $this->_app_path,$paths ) === false) {
array_push ( $paths,$this->_app_path );
}
if (array_search ( $this->_framework_path,$paths ) === false) {
array_push ( $paths,$this->_framework_path );
}
set_include_path ( implode ( PATH_SEPARATOR, $paths ) ); spl_autoload_register (); } /** * links to the app and framework default config files and inits them * registers autoloader */ private function init() {$config_file = '/config/config.ini.php';
$config_files ['DH_MVC'] = __DIR__ .$config_file; //framework config
$config_files ['APP'] =$this->_app_path . $config_file; //app config$this->_config = new Config ( $config_files );$config_paths = $this->_config->get_paths ();$this->_autoloader = new Basic_Autoloader ( $config_paths ); } /** * creates new base router instance which reads the url request and routes * application onto Action Controllers */ public function run() {$this->_router = new Base_router ( $this->_config );$route = $this->_router->run (); if ($route) {
$this->_dispatcher = new Base_Dispatcher ($route );
$this->_dispatcher->run (); } } }  Not moved the initialization of new router to construct in order to remove protected $_config as I might use this attribute depending on how I develop the class. If not used I will remove.

$config_files ['DH_MVC'] = __DIR__ .$config_file;

It uses __DIR__ as $_framework_path is parent of DIR.$_framework_path takes into account my namespace dh_mvc2 thats used as the first directory, by the spl_autoload, from the framework basepath

namespace dh_mvc2\application;

use dh_mvc2\classes\Config;
use dh_mvc2\dispatchers\Base_Dispatcher;
use dh_mvc2\routers\Base_Router;

class Application {
protected $_config; protected$_autoloader;
protected $_app_path; protected$_framework_path;
protected $_router; protected$_dispatcher;

/**
*
* @param string $app_path * "path/to/application/directory"; * @throws \DH_MVC2_Application_Exeption */ public function __construct($app_path, $run = TRUE) { if (! is_dir ($app_path )) {
require_once 'exeptions/DH_MVC2_Application_Exeption.php';
throw new \DH_MVC2_Application_Exeption ( "Must supply a path to an application directory" );
}

$this->_framework_path = realpath ( dirname ( __DIR__ ) );$this->_app_path = $app_path;$this->set_ini_default_paths ();
$this->init ();$d = new Config ();
if ($run) {$this->run ();
}
}

/**
* add the framework dir and application dir to include path
*/
private function set_ini_default_paths() {
$paths = explode ( PATH_SEPARATOR, get_include_path () ); array_push ($paths, $this->_app_path ); array_push ($paths, $this->_framework_path );$paths = array_unique ( $paths ); set_include_path ( implode ( PATH_SEPARATOR,$paths ) );
}

/**
* links to the app and framework default config files and inits them
*/
private function init() {
$config_file = '/config/config.ini.php';$config_files ['DH_MVC'] = __DIR__ . $config_file; // framework config$config_files ['APP'] = $this->_app_path .$config_file; // app config
$this->_config = new Config ($config_files );
$config_paths =$this->_config->get_paths ();
$this->_autoloader = new Basic_Autoloader ($config_paths );
}

/**
* creates new base router instance which reads the url request and routes
* application onto Action Controllers
*/
public function run() {
$this->_router = new Base_router ($this->_config );
$route =$this->_router->run ();

if ($route) {$this->_dispatcher = new Base_Dispatcher ( $route );$this->_dispatcher->run ();
} else {
require_once 'exeptions/DH_MVC2_Router_Exeption.php';
throw new \DH_MVC2_Router_Exeption ( "Failed to discover route" );
}
}
}

this looks pretty good to me.

Some thoughts for entertainment;

• If you created the router in init(), then _config would not be required any more as a protected property, one less private property

• There seems to be no error handling when $this->_router->run () fails. • set_ini_default_paths violates DRY, but only once, have you considered just adding the paths and then calling array_unique. Not sure that is the right way to go, but it could be considered. • _autoloader is nowhere used, and it is private. Seems pointless? • Should $config_files ['DH_MVC'] = __DIR__ . $config_file; not use $this->_framework_path ?

• Thanks Tom. The autoloader class registers an spl_autoload_register callback function that uses the conifg paths passed to its constructor. The call back function is one of the autoloaders own methods. Hopefully allowing me to inherit and override the autoload callback for other 'types' of autoloaders. If that all made sense? Mar 19 '13 at 18:20
• your other points will be implemented now though. Well after looking at that array function to try fix the DRY issue Mar 19 '13 at 18:22

I have some criticism on details you didn't ask, but which should be addressed:

Make use of it! There is no need to make manual calls to require_once().

There even is a standard: PSR-0, which defines how you should structure your class and namespace names together with the directory and file structure. When I look at your code, I see some issues: Because the underscore was used as a separator before PHP got namespaces, it is considered a separation character in class names.

### Namespaces

Make use of it! I cannot see a reason why the exception \DH_MVC2_Application_Exeption is located in the root namespace, and not called \dh_mvc2\application\Exception. It would be so much easier to simply throw new Exception(); inside the "\dh_mvc2\application" namespace.

### Whitespace and coding style

Endless debates might occur, but I really don't like yours. Especially the inconsistent placement of parentheses. Personally, I'd rather prefer not to use that much spaces, but if you really have to, use them everywhere. For example, if you want to find the function "set_ini_default_paths", and want to make sure not to find "set_ini_default_paths_directory", you'd search for "set_ini_default_paths(" - which will find only function definitions, but not usage. To find these, you'd have to search "set_ini_default_paths (".

### Dependency injection

Doesn't take place. Objects are created inside your class. There is no way I would be able to change for example the Config object if I'd use your class, I must use yours. I even cannot change the config filename!

### Include path

Be careful what you add here. If a PSR-0 autoloader is used, there is no need to add anything to the include path. In fact, you'll get a good amount of performance if you include as few directories as possible, preferably only ".", to be able to include files with a relative path.

• Thanks Sven. I'm kind of confused with the DI thing people keep mentioning. Mar 21 '13 at 10:22
• Zend framework for example (ignoring the code) needs its config and application configs defined a certain way right? ok admittedly you can define the config zend uses in one of several ways but still define to their framework standard? And also i may be mistaken but Zend also requires the config to be in a set place within dir structure and without checking, named to a set convention also? Mar 21 '13 at 10:25
• Your comments about Namespaces and auto-loading though I understand. And currently trying to get both to work correctly without require/includes. My class would still be called DH_MVC2_Application_Exeption but located in the dir dh_mvc2\application\Exception right? Mar 21 '13 at 10:33
• Looking at zend again, with respect to configs. You can specify the path to config file, and can have one of several formats. So maybe i should allow for my config to be located anywhere. But i'm still confused as to why requiring-'coupling' my application class to use a 'known' config (and autoloader) is wrong. Am i missing something big here? Or could i write a config file/autoloader how i wanted and throw it at zend and other frameworks and they would happily use them? Mar 21 '13 at 11:25
• I think i figured out why I was struggling with auto-loading thanks to your link to the PSR-0. DH_MVC2_Application_Exception would work if my directory was DH/MVC2/Application/Exception but my root dir was DH_MVC2 which auto-loader resolves as DH/MVC2 (if i understand it right?). Thank you for that Mar 21 '13 at 12:45


text:
Question

# $ABCD$ is a parallelogram and $AP$ and$CQ$ are perpendiculars from vertices $A$ and $C$ on diagonal $BD$. Show that $\left(\mathrm{i}\right)\mathrm{\Delta APB}\cong \mathrm{\Delta CQD}$ $\left(\mathrm{ii}\right)\mathrm{AP}=\mathrm{CQ}$

Open in App
Solution

## Step $1:$ Drawing the diagram:$ABCD$ is a parallelogram$AP$ and $CQ$ are perpendiculars from vertices $A$ and $C$ on diagonal $BD$.Step $2:$ Proving $\mathrm{\Delta APB}\cong \mathrm{\Delta CQD}$:In, $\mathrm{\Delta APB}$ and $\mathrm{\Delta CQD}$$\begin{array}{rcl}\angle \mathrm{APB}& =& \angle \mathrm{CQD}\left(\mathrm{Each}\mathrm{equals}\mathrm{to}90°\right)\\ \angle \mathrm{ABP}& =& \angle \mathrm{CDQ}\left(\mathrm{Alternate}\mathrm{interior}\mathrm{angles}\mathrm{for}\mathrm{AB}\parallel \mathrm{CD}\right)\\ \mathrm{AB}& =& \mathrm{CD}\left(\mathrm{Opposite}\mathrm{sides}\mathrm{of}\mathrm{parallelogram}\mathrm{ABCD}\mathrm{are}\mathrm{equal}\right)\end{array}$$\therefore △\mathrm{APB}\cong △\mathrm{CQD}\left(\mathrm{By}\mathrm{AAS}\mathrm{congruency}\mathrm{criteria}\right)$Step $3:$ Proving $\mathrm{AP}=\mathrm{CQ}$$\therefore \mathrm{AP}=\mathrm{CQ}\left(\mathrm{By}\mathrm{CPCT}\right)$Hence proved.

Suggest Corrections
21
Related Videos
Parallelograms
MATHEMATICS
Watch in App
Explore more


text:
# Sections

In addition to the document title (level 0), AsciiDoc supports four section levels: 1 (top) to 4 (bottom). Section levels are delimited by section titles. Sections are translated using configuration file section markup templates. AsciiDoc generates the following intrinsic attributes specifically for use in section markup templates:

level
The level attribute is the section level number, it is normally just the title level number (1..4). However, if the leveloffset attribute is defined it will be added to the level attribute. The leveloffset attribute is useful for combining documents.
sectnum
The -n (--section-numbers) command-line option generates the sectnum (section number) attribute. The sectnum attribute is used for section numbers in HTML outputs (DocBook section numbering are handled automatically by the DocBook toolchain commands).

#### Section markup templates

Section markup templates specify output markup and are defined in AsciiDoc configuration files. Section markup template names are derived as follows (in order of precedence):

1. From the title’s first positional attribute or template attribute. For example, the following three section titles are functionally equivalent:
[[terms]]
[glossary]
List of Terms
-------------

["glossary",id="terms"]
List of Terms
-------------

[template="glossary",id="terms"]
List of Terms
-------------
2. When the title text matches a configuration file [specialsections] entry.
3. If neither of the above the default sect<level> template is used (where <level> is a number from 1 to 4).

In addition to the normal section template names (sect1, sect2, sect3, sect4) AsciiDoc has the following templates for frontmatter, backmatter and other special sections: abstract, preface, colophon, dedication, glossary, bibliography, synopsis, appendix, index. These special section templates generate the corresponding Docbook elements; for HTML outputs they default to the sect1 section template.

#### Section IDs

If no explicit section ID is specified an ID will be synthesised from the section title. The primary purpose of this feature is to ensure persistence of table of contents links (permalinks): the missing section IDs are generated dynamically by the JavaScript TOC generator after the page is loaded. If you link to a dynamically generated TOC address the page will load but the browser will ignore the (as yet ungenerated) section ID.

The IDs are generated by the following algorithm:

• Replace all non-alphanumeric title characters with underscores.
• Strip leading or trailing underscores.
• Convert to lowercase.
• Prepend the idprefix attribute (so there’s no possibility of name clashes with existing document IDs). Prepend an underscore if the idprefix attribute is not defined.
• A numbered suffix (_2, _3 …) is added if a same named auto-generated section ID exists.
• If the ascii-ids attribute is defined then non-ASCII characters are replaced with ASCII equivalents. This attribute may be deprecated in future releases and should be avoided, it’s sole purpose is to accommodate deficient downstream applications that cannot process non-ASCII ID attributes.

Example: the title Jim’s House would generate the ID _jim_s_house.

Section ID synthesis can be disabled by undefining the sectids attribute.

#### Special Section Titles

AsciiDoc has a mechanism for mapping predefined section titles auto-magically to specific markup templates. For example a title Appendix A: Code Reference will automatically use the appendix section markup template. The mappings from title to template name are specified in [specialsections] sections in the Asciidoc language configuration files (lang-*.conf). Section entries are formatted like:

<title>=<template>

<title> is a Python regular expression and <template> is the name of a configuration file markup template section. If the <title> matches an AsciiDoc document section title then the backend output is marked up using the <template> markup template (instead of the default sect<level> section template). The {title} attribute value is set to the value of the matched regular expression group named title, if there is no title group {title} defaults to the whole of the AsciiDoc section title. If <template> is blank then any existing entry with the same <title> will be deleted.

 Special section titles vs. explicit template names AsciiDoc has two mechanisms for specifying non-default section markup templates: you can specify the template name explicitly (using the template attribute) or indirectly (using special section titles). Specifying a section template attribute explicitly is preferred. Auto-magical special section titles have the following drawbacks: They are non-obvious, you have to know the exact matching title for each special section on a language by language basis. Section titles are predefined and can only be customised with a configuration change. The implementation is complicated by multiple languages: every special section title has to be defined for each language (in each of the lang-*.conf files). Specifying special section template names explicitly does add more noise to the source document (the template attribute declaration), but the intention is obvious and the syntax is consistent with other AsciiDoc elements c.f. bibliographic, Q&A and glossary lists. Special section titles have been deprecated but are retained for backward compatibility.


text:
# square of a function is not integrable

• Aug 16th 2011, 01:03 PM
parklover
square of a function is not integrable
Is there a function f: R->R is integrable but f^2 is not? why?
• Aug 16th 2011, 01:17 PM
Plato
Re: square of a function is not integrable
Quote:

Originally Posted by parklover
Is there a function f: R->R is integrable but f^2 is not? why?

Theorem: If $f$ is an integrable function in $[a,b]$ then $f^2$ is an integrable function in $[a,b]$.

P.S. In response to the to reply #3.
It depends on how one defines integral.
Most often Riemann integrals require bounded functions.
That example is not a bounced function.
The term is improper integral.
• Aug 16th 2011, 01:32 PM
girdav
Re: square of a function is not integrable
Consider $f(x) =\begin{cases} \frac 1{\sqrt{|x|}}&\mbox{if } -1\leq x<0 \mbox{ or }01 \end{cases}$ and choose any value you want for $x=0$.
• Aug 16th 2011, 01:51 PM
parklover
Re: square of a function is not integrable
Quote:

Originally Posted by girdav
Consider $f(x) =\begin{cases} \frac 1{\sqrt |x|}&\mbox{if } -1\leq x<0 \mbox{ or }01 \end{cases}$ and choose any value you want for $x=0$.

sorry, I am slow. why is it not integrable？i think ln (x)
• Aug 16th 2011, 01:59 PM
girdav
Re: square of a function is not integrable
The function $f$ is integrable but not its square. As you noticed, a primitive of $\frac 1x$ is $\ln x$, but if you compute $\int_{\varepsilon}^1\frac 1xdx$, you will find $-\ln \varepsilon$, and it has an infinite limit as $\varepsilon\to 0$.
• Aug 16th 2011, 02:00 PM
Plato
Re: square of a function is not integrable
Quote:

Originally Posted by parklover
sorry, I am slow. why is it not integrable？i think ln (x)

The function $\frac{1}{\sqrt{|x|}}$ is not Riemann integrable on $[-1,0]$.
However as an improper integral $\int_{ - 1}^0 {\frac{{dx}}{{\sqrt {\left| x \right|} }}}=2$.
But $\int_{ - 1}^0 {\frac{{dx}}{{ {\left| x \right|} }}}$ does not exist even as an improper integral.


text:
# Conservation of angular momentum in rotational spectroscopy

In spectroscopy, transitions between rotational energy levels obey the selection rule $\Delta J = \pm1$. The rule follows from the fact that the photon absorbed has an angular momentum of $\pm \hbar$, so the molecule must change its angular momentum for the total angular momentum to be conserved.

However, the angular momentum of a molecule is given by $\hbar \sqrt{J(J+1)}$, so the change in molecular ang. mom. is $\hbar\sqrt{(J+1)(J+2)} - \hbar\sqrt{J(J+1)}$. As $\hbar\sqrt{(J+1)(J+2)} - \hbar\sqrt{J(J+1)} \neq \hbar$, it seems that the total angular momentum is not actually conserved.

Questions:

• Does the conservation of angular momentum apply to quantum systems?
• If yes, what is the source of the contradiction above?
• To the first question: Yes Oct 29 '17 at 12:41
• @user1420303 thanks! What about the second one! Oct 29 '17 at 12:43
• Angular momentum is a vector and the addition of the angular momentum of the photon to that of the molecule has to follow the rules for vector addition. That means that you first have to add these two vectors together before you can take the operator of the total angular momentum.
– Paul
Oct 30 '17 at 8:11
• @Paul, I see why $\hbar\sqrt{(J+1)(J+2)} – \hbar\sqrt{J(J+1)}$ can be smaller than $\hbar$ because of vector addition, but it's in fact greater than that, so I don't see how this helps -- could you please clarify? Also, what do you mean by "add vectors together before your can take the operator of the total angular momentum" -- do you mean add vectors, then get the magnitude of the sum? If so, this still doesn't explain why the increase is greater than what one would expect even if vectors were aligned. And thanks for your help! Nov 1 '17 at 21:11
• Before the absorption takes place the total angular momentum in the system is given by $\vec{J}=\vec{j}+\vec{j}_\text{ph}$ where $\vec{j}$ and $\vec{j}_\text{ph}$ are the angular momenta of the molecule and photon respectively. The total angular momentum operator is thus $\hat{J}^2=(\hat{j}+\hat{j}_\text{ph})^2=\hat{j}^2+\hat{j}_\text{ph}^2+2\hat{j}\hat{j}_\text{ph}$. In your treatment you have ignored the last term (you only add the angular momentum of the individual molecule and photon and ignore their interaction). A proper evaluation involves quite some angular momentum algebra.
– Paul
Nov 2 '17 at 11:28

Sorry for the late answer, but I could not find the time to write something earlier. A concept that you encounter often in quantum mechanics is the so-called coupled and uncoupled basis. Your question is a variation on that theme: before the absorption the uncoupled representation is the more natural where the angular momentum of the photon and the angular momentum of the molecule (and their projections) are good quantum numbers, whereas after the absorption the coupled representation is more suitable and the total angular momentum of the system (and it's projection) is a good quantum number. In Dirac's braket notation we have

$$|jm_j\rangle |j_\text{ph}m_{j_{\text{ph}}}\rangle$$ for the uncoupled representation and $$|JM_J\rangle$$ for the coupled representation.

Your question concerns the conservation of the total angular momentum of the system $\hat{J}^2$ and in the coupled representation the expectation values are easily obtained because $J$ is a good quantum number $$\hat{J}^2|JM_J\rangle=\hbar^2 J(J+1)|JM_J\rangle$$

In the uncoupled representation the total angular momentum is given by $\hat{J}^2=\left ( \hat{j}+\hat{j}_\text{ph} \right)^2=\hat{j}^2+\hat{j}_\text{ph}^2+2\hat{j}\cdot \hat{j}_\text{ph}$

The first two terms of this expression are again easy, but the thrid term is a bit tricky. Using the ladder operators you can write it as $$2\hat{j}\cdot \hat{j}_\text{ph}=2(\hat{j}_x\hat{j}_{\text{ph},x}+\hat{j}_y\hat{j}_{\text{ph},y}+\hat{j}_z\hat{j}_{\text{ph},z})=\hat{j}_+\hat{j}_{\text{ph},-}+\hat{j}_-\hat{j}_{\text{ph},+}+2\hat{j}_z\hat{j}_{\text{ph},z}$$ where $$\hat{j}_\pm|jm_j\rangle=\hbar\sqrt{j(j+1)-m(m\pm1)}|jm_j\pm1\rangle$$ and it thus couples states of different $m_j$. Let us, for example, couple $|jm_j\rangle=|1m_j\rangle$ and $|j_\text{ph}m_{j_\text{ph}}\rangle=|1m_{j_\text{ph}}\rangle$ so that we have $(2j+1)(2j_\text{ph}+1)=9$ basis states: $$|1,-1\rangle|1,-1\rangle,\\|1,-1\rangle|1,0\rangle,\\|1,-1\rangle|1,1\rangle,\\ |1,0\rangle|1,-1\rangle,\\|1,0\rangle|1,0\rangle,\\|1,0\rangle|1,1\rangle,\\ |1,1\rangle|1,-1\rangle,\\|1,1\rangle|1,0\rangle,\\|1,1\rangle|1,1\rangle$$

We determine all expectation values of the total angular momentum operator using the 9 basis states which gives us a total of 81 values that we can order in a 9x9 matrix (in units of $\hbar^2$)

6   0   0   0   0   0   0   0   0
0   4   0   2   0   0   0   0   0
0   0   2   0   2   0   0   0   0
0   2   0   4   0   0   0   0   0
0   0   2   0   4   0   2   0   0
0   0   0   0   0   4   0   2   0
0   0   0   0   2   0   2   0   0
0   0   0   0   0   2   0   4   0
0   0   0   0   0   0   0   0   6

We can diagonalize this matrix and find the eigenvalues 0, 2, 2, 2, 6, 6, 6, 6, 6. These are the same eigenvalues (including the $2J+1$ degeneracy) of $\hat{J}^2$ in the coupled representation!

So the expectation value of the total angular momentum is the same in both cases, the difference is that in the uncoupled case the matrix has off-diagonal elements and it is a bit more work to find its eigenvalues. In the coupled case, the matrix for $\hat{J}^2$ is diagonal and you get the expectation values directly. You might ask if there is an easier way to convert from the coupled to the uncoupled case and back. As you might have guessed there is such a way and it involves the so-called Clebsch-Gordan coefficients.


text:
$$\require{cancel}$$

# 1.1: Breakdown of Classical Mechanics

## What was Wrong with Classical Mechanics?

Basically, classical statistical mechanics wasn’t making sense...

Maxwell and Boltzmann evolved the equipartition theorem: a physical system can have many states (gas with particles having different velocities, or springs in different states of compression).

At nonzero temperature, energy will flow around in the system, it will constantly move from one state to another. So, what is the probability that at any instant it is in a particular state with energy $$E$$?

M&B proves it was proportional to $$e^{-E/kT}$$. This proportionality factor is also correct for any subsystem of the system: for example a single molecule.

Notice this means if a system is a set of oscillators, different masses on different strength springs, for example, then in thermal equilibrium each oscillator has on average the same energy as all the others. For three-dimensional oscillators in thermal equilibrium, the average energy of each oscillator is $$3kT$$, where $$k$$ is Boltzmann’s constant.

Now put this together with Maxwell’s discovery that light is an electromagnetic wave: inside a hot oven, Maxwell’s equations can be solved yielding standing wave solutions, and the set of different wavelength allowed standing waves amount to an infinite series of oscillators, with no upper limit on the frequencies on going far into the ultraviolet. Therefore, from the classical equipartition theorem, an oven at thermal equilibrium at a definite temperature should contain an infinite amount of energy—of order $$kT$$ in each of an infinite number of modes—and if you let radiation out through a tiny hole in the side, you should see radiation of all frequencies.

This is not, of course, what is observed: as an oven is warmed, it emits infrared, then red, then yellow light, etc. This means that the higher frequency oscillators (blue, etc.) are in fact not excited at low temperatures: equipartition is not true.

Planck showed that the experimentally observed intensity/frequency curve was exactly reproduced if it was assumed that the radiation was quantized: light of frequency $$f$$ could only be emitted in quanta—now photons—having energy $$hf$$, $$h$$ being Planck’s constant. This was the beginning of quantum mechanics.

## The Photoelectric Effect

Einstein showed the same quantization of electromagnetic radiation explained the photoelectric effect: a photon of energy $$hf$$ knocks an electron out of a metal, it takes a certain work $$W$$ to get it out, the rest of the photon energy goes to the kinetic energy of the electron, for the fastest electrons emitted (those that come right from the surface, so encountering no further resistance). Plotting the maximum electron kinetic energy as a function of incident light frequency confirms the hypothesis, giving the same value for $$h$$ as that needed to explain radiation from an oven. (It had previously been assumed that more intense light would increase the kinetic energy—this turned out not to be the case.)

## The Bohr Atom

Bohr put together this quantization of light energy with Rutherford’s discovery that the atom had a nucleus, with electrons somehow orbiting around it: for the hydrogen atom, light emitted when the atom is thermally excited has a particular pattern, the observed emitted wavelengths are given by

$\dfrac{1}{\lambda}=R_H\left(\dfrac{1}{4}-\dfrac{1}{n^2}\right) \tag{1.1.1}$

with $$n = 3, 4, 5...$$ $$R_H$$ is now called the Rydberg constant.) Bohr realized these were photons having energy equal to the energy difference between two allowed orbits of the electron circling the nucleus (the proton), $$E_n -E_m =hf$$, leading to the conclusion that the allowed levels must be:

$E_n =-\dfrac{hcR_H}{n^2} \tag{1.1.2}$

How could the quantum $$hf$$ restricting allowed radiation energies also restrict the allowed electron orbits? Bohr realized there must be a connection—because $$h$$ has the dimensions of angular momentum! What if the electron were only allowed to be in circular orbits of angular momentum $$nKh$$, with $$n$$ an integer? Bohr did the math for orbits under an inverse square law, and found that the observed spectra were in fact correctly accounted for by taking $$K = 1/2\pi$$.

But then he realized he did not even need the experimental results to find $$K$$: quantum mechanics must agree with classical mechanics in the regime where we know experimentally that classical mechanics (including Maxwell’s equations) is correct, that is, for systems of macroscopic size. Consider a negative charge orbiting around a fixed positive charge at a radius of 10 cm., the charges being such that the speed is of order meters per second (we don’t want relativistic effects making things more complicated). Then from classical E&M, the charge will radiate at the orbital frequency. Now imagine this is actually a hydrogen atom, in a perfect vacuum, in a high state of excitation. It must be radiating at this same frequency. But Bohr’s theory can’t just be right for small orbits, so the radiation must satisfy $$E_n -E_m =hf$$. The spacing between adjacent levels will vary slowly for these large orbits, so $$h$$ times the orbital frequency must be the energy difference between adjacent levels. Now, that energy difference depends on the allowed angular momentum step between the adjacent levels: that is, on $$K$$. Reconciling these two expressions for the radiation frequency gives $$K = 1/2\pi$$.

This classical limit argument, then, predicts the Rydberg constant in terms of already known quantities:

$R_H= \left(\dfrac{1}{4\pi\varepsilon_0} \right)^2 \cdot\dfrac{2\pi^2 me^4}{ch^3} \tag{1.1.3}$.

What’s right about the Bohr atom?

1. It gives the Balmer series spectra.
2. The first orbit size is close to the observed size of the atom: and remember there are no adjustable parameters, the classical limit argument determines the spectra and the size.

What’s wrong with the Bohr atom?

1. No explanation for why angular momentum should be quantized. (This was solved by de Broglie a little later.)
2. Why don’t the circling electrons radiate, as predicted classically? Well, the fact that radiation is quantized means the classical picture of an accelerating charge smoothly emitting radiation cannot work if the energies involved are of order $$h$$ times the frequencies involved.
3. The lowest state has nonzero angular momentum. This is a defect of the model, corrected in the truly quantum model (Schrödinger’s equation).
4. In an inverse square field, orbits are in general elliptical.

This was at first a puzzle: why should there be only circular orbits allowed? In fact, the model does allow elliptical orbits, and they do not show up in the Balmer series because, as proved by Sommerfeld, if the allowed elliptical orbits have the same allowed angular momenta as Bohr’s orbits, they have the same set of energies. This is a special property of the inverse square force. .

## De Broglie Waves

The first explanation of why only certain angular momenta are allowed for the circling electron was given by de Broglie: just as photons act like particles (definite energy and momentum), but undoubtedly are wave like, being light, so particles like electrons perhaps have wave like properties. For photons, the relationship between wavelength and momentum is $$p = h/\lambda$$. Assuming this is also true of electrons, and that the allowed circular orbits are standing waves, Bohr’s angular momentum quantization follows.

## Schrödinger’s Wave Equation

De Broglie’s idea was clearly on the right track—but waves in space are three-dimensional, thinking of the circular orbit as a string under tension cannot be right, even if the answer is.

Photon waves (electromagnetic waves) obey the equation

$\nabla^2 \vec E -\dfrac{1}{c^2} \dfrac{\partial^2 \vec E}{\partial t^2}=0 \tag{1.1.4}$

A solution of definite momentum is the plane wave

$\left(\dfrac{\partial^2}{\partial x^2} -\dfrac{1}{c^2}\dfrac{\partial^2}{\partial t^2} \right) \vec E_0 e^{i(kx-\omega t)} = \left(k^2 -\dfrac{\omega^2}{c^2} \right)\vec E_0 e^{i(kx-\omega t)} =0 \tag{1.1.5}$

Notice that the last equality is essentially just $$\omega =ck$$, where for a plane wave solution the energy and momentum of the photon are translated into differential operators with respect to time and space respectively, to give a differential equation for the wave.

Schrödinger’s wave equation is equivalently taking the (nonrelativistic) energy-momentum relation $$E = p^2/2m$$ and using the same recipe to translate it into a differential equation:

$i\hbar \dfrac{\partial \psi(x,t)}{\partial t} =-\dfrac{\hbar^2}{2m} \dfrac{\partial^2 \psi(x,t)}{\partial x^2} \tag{1.1.6}$

Making the natural extension to three dimensions, and assuming we can add a potential term in the most naïve way possible, that is, going from $$E = p^2/2m$$ to $$E = p^2/2m + V(x,y,z)$$, we get

$i\hbar \dfrac{\partial \psi(x,y,z,t)}{\partial t}=-\dfrac{\hbar^2}{2m} \nabla^2 \psi(x,y,z,t) +V(x,y,z) \psi(x,y,z,t) \tag{1.1.7}$

This is the equation Schrödinger wrote down and solved, the solutions gave the same set of energies as the Bohr model, but now the ground state had zero angular momentum, and many of the details of the solutions were borne out by experiment, as we shall discuss further later.

## A Conserved Current

Schrödinger also showed that a conserved current could be defined in terms of the wave function $$\psi$$:

$\dfrac{\partial \rho}{\partial t} +div \vec j =0 \tag{1.1.8}$

where

• $$\rho =\psi^\ast \psi =|\psi |^2$$ and
• $$\vec j =\dfrac{\hbar}{2mi} (\psi^\ast \vec \nabla \psi -\psi \vec \nabla \psi^\ast ).$$

Schrödinger’s interpretation of his equation was that the electron was simply a wave, not a particle, and this was the wave intensity. But thinking of electromagnetic waves in this way gave no clue to the quantum photon behavior—this could not be the whole story.

## Interpreting the Wave Function

The correct interpretation of the wave function (due to Born) follows from analogy to the electromagnetic case. Let’s review that briefly. The basic example is the two-slit diffraction pattern, as built up by sending through one photon at a time, to a bank of photon detectors. The pattern gradually emerges: solve the wave equation, then the predicted local energy density (proportional to $$|E(x,y,z,t)|^2 dxdydz$$) gives the probability of one photon going through the system landing at that spot.

Born suggested that similarly $$|\psi |^2$$ at any point was proportional to the probability of detecting the electron at that point. This has turned out to be correct.

## Localizing the Electron

Despite its wavelike properties, we know that an electron can behave like a particle: specifically, it can move as a fairly localized entity from one place to another. What’s the wave representation of that? It’s called a wave packet: a localized wave excitation. To see how this can come about, first remember that the Schrödinger equation is a linear equation, the sum of any two or more solutions is itself a solution. If we add together two plane waves close in wavelength, we get beats, which can be regarded as a string of wave packets. To get a single wave packet, we must add together a continuous range of wavelengths.

The standard example is the Gaussian wave packet, $$\psi (x, t=0) =A e^{ik_0 x} e^{-x^2 /2 \Delta^2}$$ where $$p_0 = \hbar k_0$$

Using the standard result $\int\limits_{-\infty}^{+\infty} e^{-a x^2}\,dx = \sqrt{ \frac{ \pi}{a}} \tag{1.1.9}$

we find $$|A|^2 =(\pi \Delta^2)^{-1/2}$$ so $\psi (x,t=0) =\frac{1}{(\pi \Delta^2)^{1/4}} e^{ik_0 x} e^{-x^2 /2 \Delta^2} . \tag{1.1.10}$

But how do we construct this particular wavepacket by superposing plane waves? That is to say, we need a representation of the form: $\psi(x) =\int\limits_{-\infty}^{+\infty} \frac{dk}{2\pi} e^{ikx} \phi (k) \tag{1.1.11}$

The function $$\phi(k)$$ represents the weighting of plane waves in the neighborhood of wavenumber $$k$$. This is a particular example of a Fourier transform—we will be discussing the general case in detail a little later in the course. Note that if $$\phi(k)$$ is a bounded function, any particular $$k$$ value gives a vanishingly small contribution, the plane-wave contribution to $$\psi(x)$$ from a range $$dk$$ is $$\phi(k) dk/2\pi$$. In fact, $$\phi(k)$$ is given in terms of $$\psi(x)$$ by $\phi(k) =\int\limits_{-\infty}^{+\infty} dxe^{-ikx} \psi(x) . \tag{1.1.12}$

It is perhaps worth mentioning at this point that this can be understood qualitatively by observing that the plane wave prefactor $$e^{-ikx}$$ will interfere destructively with all plane wave components of $$\psi(x)$$ except that of wavenumber $$k$$, where it may at first appear that the contribution is infinite, but recall that as stated above, any particular $$k$$ component has a vanishingly small weight—and, in fact, this is the right answer, as we shall show in more convincing fashion later.

In the present case, the above handwaving argument is unnecessary, because both the integrals can be carried out exactly, using the standard result: $\int\limits_{-\infty}^{\infty} e^{-ax^2 +bx}\, dx =e^{b^2 /4a}\sqrt{\frac{\pi}{a}} \tag{1.1.13}$

giving $\phi(k) =(4\pi \Delta^2)^{\frac{1}{4}} e^{-\Delta^2 (k-k_0)^2 /2} . \tag{1.1.14}$.

## The Uncertainty Principle

Note that the spreads in x-space and p-space are inversely related: $$\Delta x$$ is of order $$\Delta$$, $$\Delta p=\hbar \Delta k\sim \hbar/\Delta$$. This is of course the Uncertainty Principle, localization in x-space requires a large spread in contributing momentum states.

It’s worth reviewing the undergraduate exercises on applications of the uncertainty principle. The help sharpen one’s appreciation of the wave/particle nature of quantum objects.

There’s a limit to how well the position of an electron can be determined: it is detected by bouncing a photon off of it, and the photon wavelength sets the limit on $$\Delta x$$. But if the photon has enough energy to create an electron-positron pair out of the vacuum, you can’t be sure which electron you’re seeing. This limits $$\Delta x \sim \hbar/mc$$ at best. (This is called the Compton wavelength, written $$\lambda_c$$ – it appears in Compton scattering.) How much smaller that a hydrogen atom ground state wave function is this? $$\lambda_c /a_0 =e^2/\hbar c (CGS)=e^2/4\pi \varepsilon_0 \hbar c (SI)=1/137$$, known as the fine structure constant. This is also the ratio of the electron speed in the first Bohr orbit to the speed of light, and so is an indication of the importance of relativistic corrections to energies of electron states; these differences in electron orbit energies for circular and elliptical states having the same energy when calculated nonrelativistically lead to fine structure in the atomic spectra.

## Contributor

1.1: Breakdown of Classical Mechanics is shared under a not declared license and was authored, remixed, and/or curated by Michael Fowler via source content that was edited to conform to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.


text:
## Loser66 one year ago Number theory question. Please, give me a concrete example for this. I would like to understand what is going on.

1. Loser66

2. Loser66

@imqwerty

3. imqwerty

ok so we wanna find the largest power of p which divides n! right?

4. imqwerty

so we wanna find the largest power of p contained in n! it wuld be [n/p] +[n/p^2]+[n/p^3]...... [ ] <---greatest integer function the proof of this formula can be obtained using the fact that [n/m] will give the number of integral multiples of m in n. note that this formula will wrk only if n is prime EXAMPLE- if we have- find the number of 0s at the end of 130! - SOLUTION the number of 0s at the end is equal to the exponent of 10 in 130!. now exponent of 10 (or 5x2) is equal to exponent of 5 as exponent of 2 will we lager so we find exponent of 5 in 130! [130/5]+[130/25]+[130/125]+[130/625].... 26+5+1+0+0+0.....and all will be 0 cause the denominator>numerator =32 so power of 10 =32 so no of zeros =32

5. Loser66

"note that this formula will wrk only if n is prime" , it is not true. it must be true for all n . Like if n = 300, and p is a prime 11, then the number divides 300 is $$\lfloor 300/11\rfloor = \lfloor 27.27\rfloor = 27$$ , that is {11, 22, 33, 44,55, 66,.........}

6. imqwerty

wait sry its not n it should be p=prime :)

7. Loser66

" power of 10 =32" means $$10^{32}$$ is the largest power of 10 , right? and it is found by formula [130/5] +[130/25] + [130/125]+..... right?

8. imqwerty

yes :)

9. Loser66

But I still not see the link between 130 and 130! :(

10. imqwerty

umm u confused with that [n/m] part which i said?

11. Loser66

I understand that for n = 130, then there are 26 numbers which are multiple of 5 divide 130. there are 5 numbers which are multiple of 25 divide 130 there are 1 numbers which are multiple of 125 divide 130 and sum of them is 32. But that is we are working on 130, not 130! , am I missing something?

12. Loser66

Take a smaller number, please, like n = 9, then n!= 3628880

13. Loser66

3 is too big, take 101, please

14. Loser66

Hence if n =9 , n! = 3628880 , let m =n!, prime p = 101 As the statement, $$\lfloor m/p \rfloor + \lfloor m/p^2\rfloor+\lfloor m/p^3\rfloor +\cdots = 3592+355+3+0+....+0=3950$$

15. imqwerty

XD n!=3628880 ok but we have to do it the same way it wuld be- $\left[ \frac{ 3628880 }{ 101 }\right]+\left[ \frac{ 3628880 }{ 101^2 }\right]+\left[ \frac{ 3628880 }{ 101^3 }\right].....$ =35929+355+3+0+0..=36287 suppose we want to find the power of 3 in 1200 we take 1200 in numerator part because we wanna find the number of integral multiples 1st we calculate [1200/3] =400 1200!=1200 x 1119 x 1118 x 1117........2x1 now we knw that under 1200 there are 400 numbers that are divisible by 3 when we opened 1200! those must are there in the list for example in those 400 numbers 12 and 15 must be there and 12, 15 must have appeared when we open 1200! we can write 12=3x4 adn 15=3x5 and there are 400 such numbers so 400 3s must have appeared :) and like this we calculate the multiples of 9, 27 ad so on...and add them cause the sum total of them is the number of times 3 appeared when we opened the factorial

16. ganeshie8

9! = 1*2*3*4*5*6*7*8*9 suppose we want to find the exponent of 3 in the prime factorization of 9! First, may be try answering a simpler question : How many numbers are divisible by 3 that are less than or equal to 9 ?

17. Loser66

3

18. ganeshie8

Right, how did u get 3 ?

19. Loser66

$$(9,n) \neq 1$$

20. ganeshie8

could you elaborate on how you got 3

21. Loser66

$$(9,3) =3 \neq 1$$ , hence 3 is the first one $$9,6) = 3\neq 1$$ hence 6 is the second one $$9,9) =9\neq 1$$ hence 9 is the third one therefore there are 3 numbers

22. Loser66

oh, you want me to settle down it to multiple of 3, got it.

23. ganeshie8

Okay, good. for now yes, lets just focus on numbers that are divisible by 3 only

24. ganeshie8

consider the set of integers : $$\{1, 2, 3, \ldots, n\}$$ It is easy to see that there are "approximately" $$\dfrac{n}{p}$$ integers that are divisible by $$p$$, yes ?

25. Loser66

yes,

26. ganeshie8

Try finding the "exact" count by considering few examples

27. Loser66

is it not that it is the floor of n/p. Like if n = 9 as above and p =2, then there are $$\lfloor 9/2\rfloor = 4$$ number on 9! = 1*2*3*4*5*6*7*8*9 divides 9, that is 2, 4, 6,8 which is power of 2 on 9!

28. ganeshie8

Exactly! similarly, how many integers in that list are divisible by $$p^2$$ ?

29. Loser66

$$\lfloor n/p^2\rfloor$$

30. Loser66

in our concrete example, it is just 1, right?

31. Loser66

that is 4, (2^2)

32. ganeshie8

Yes. More genereeally, can we say : There are exactly $$\left\lfloor \dfrac{n}{p^k}\right\rfloor$$ integers that are divisible by $$p^k$$ in the set of integers $$\{1, 2, 3, \ldots, n\}$$.

33. Loser66

Yes

34. ganeshie8

Good, save that. Lets get back to the original problem

35. ganeshie8

we want to find the exponent of $$p$$ in the prime factorization of $$n!$$

36. ganeshie8

One way to do it is by finding the exponent of $$p$$ in each of the factors: $$\{1,2,3,\ldots,n\}$$, then add the exponents. But we wont do it this way as there is another really nice way to count.

37. Loser66

I am very slow, please, give me the explanation for the simple way first. I can easily understand the elegant way later if I understand the easiest one, right?

38. ganeshie8

simple way is the hack way : 1) find the exponent of $$p$$ in each of the factors in $$n!$$ 2) add them up its not really interesting

39. Loser66

Like for p, and n! = 1*2*...*p*(p+1)*....*2p*(2p+1)*.....*pp (this is p^2) *(p^2+1)*....*p^3*.............................*n and then, how to turn it to the expression above.

40. ganeshie8

$$9! = 1*2*3*4*5*6*7*8*9$$ to find the exponent of $$3$$ in the prime factorization of $$9!$$ : 1) exponent of 3 in 1 = 0, exponent of 3 in 2 = 0, exponent of 3 in 3 = 1, exponent of 3 in 4 = 0, exponent of 3 in 5 = 0, exponent of 3 in 6 = 1, exponent of 3 in 7 = 0, exponent of 3 in 8 = 0, exponent of 3 in 9 = 2, 2) add the exponents : 0 + 0 + 1 + 0 + 0 + 1 + 0 + 0 + 2 = $$4$$

41. Loser66

GGGGGGGot you

42. Loser66

Thanks for being patient to me. At the end, I got what is going on. Now, what is the elegant way?

43. ganeshie8

We have observed earlier that there are exactly $$\left\lfloor \dfrac{n}{p}\right\rfloor$$ divisors of $$p$$ in the set of integers : $$\{1,2,3,\ldots, n\}$$. These give one power of $$p$$.

44. ganeshie8

there are exactly $$\left\lfloor \dfrac{n}{p^2}\right\rfloor$$ divisors of $$p^2$$ in the set of integers : $$\{1,2,3,\ldots, n\}$$. These give another power of $$p$$.

45. ganeshie8

there are exactly $$\left\lfloor \dfrac{n}{p^3}\right\rfloor$$ divisors of $$p^3$$ in the set of integers : $$\{1,2,3,\ldots, n\}$$. These give yet another power of $$p$$.

46. ganeshie8

Continuine to infinity : exponent of $$p$$ in the prime factorization of $$n!$$ is given by $$\sum\limits_{k=1}^{\infty} \left\lfloor \dfrac{n}{p^k}\right\rfloor$$

47. Loser66

Thank you so much. I do appreciate. :)

48. ganeshie8

np :)


text:
# Commutative diagram not working on tikzcd [closed]

I'm using the \usepackage{tikz-cd} and I'm trying to make a commutative diagram.

Why doesn't this simple code work?

$$\begin{tikzcd} A \arrow {rd}{f} \arrow{r}{\phi} & B \\ & C \end{tikzcd}$$

I can't find a problem with this, but it won't compile?

## closed as unclear what you're asking by egreg, Marijn, Phelype Oleinik, Mensch, user156344 Apr 17 at 2:09

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

• if you get an error please post a small complete document and also show the exact error message from the log that you get from your test file. – David Carlisle Apr 16 at 19:55
• No error if I add a standard preamble. – egreg Apr 16 at 21:24


text:
Math Help - Prime factorization question

1. Prime factorization question

We have $E=(\mathbb{E}, +,*,0)$ where $\mathbb{E}$ is the set of even natural numbers. I know all numbers in this set can be factored into a product of $\mathbb{E}$-primes and that it is not always unique.

I'm trying to find the least even number with three factorizations and the least even number that has four factorizations.

2. $360=2(2\times 3^2)(2 \times 5) = (2 \times 3)^2(2 \times 5) = 2(2\times 3 \times 5)(2 \times 3)$

Pretty sure that's the one for three factorisations!


text:
# Possibility of determining the mass of the water without a scale?

Possibility of determining the mass of the water by knowing water volume, water temperature and atmospheric pressure.

I want to know if I can determine the mass of $V=0.01\,m^3$ of water in $T=298\,k$ and $P=1\,atm$.

So what formula should I use?

• What's the density of water? – Kyle Kanos Jul 22 '13 at 17:55
• Hint: A cubic meter is $10^6$ cubic centimeters, which, if it's full of water, is $10^6$ grams. – Mike Dunlavey Jul 22 '13 at 18:00
• wolframalpha.com/input/… – Ali Jul 22 '13 at 18:06

The density of water is, nominally, 1g/ml, but varies depending on several factors

• Impurities (dissolved ions, salts, other solutes will change the density)

Salts and ions are typically higher mass atoms/molecules than the 18atm H$_2$O molecule, as such any dissolved ions increase the mass of the liquid in the same volume and therefore increase the density, Ocean Salt water can be 3-5% more dense than freshwater at the same temperature, for instance. Salt water also depresses the freezing point and this affects the temperature dependence of the density.

• Temperature

Water density varies greatly with temperature, fresh water near boiling can be as low as 950 g/l (.95g/ml or 950kg/m$^3$) increasing as temperature decreases to a maximum at 4$^\circ$C (1g/ml) before decreasing slightly to freezing. For water room temperature and below the variation is less than $.5$% . This is by far the largest contribution to variation in density for fresh water at normal earth conditions.

• External Pressure

Liquids are relatively poorly compressible, so at atmospheric levels the atmospheric pressure will contribute negligibly to the density of water, however freezing temperatures get depressed with changes in atmospheric pressure and can affect the density vs temperature. At higher pressures the effects are more pronounced

For all of these conditions, there are really no equations to determine the density, and those that exist are typically quantitatively based on experimental measurement and apply to a certain set of conditions. THe answer is that you have to look it up based on your conditions. (Most tables for density vs temperature online are given for fresh water at 1 ATM)

Depending on the accuracy you desire you can analyze all these properties without measuring its mass to determine the density with greater precision. However for most daily uses, an estimate of 1g/ml is close enough

$$9971 \text{grams}$$


text:
Chapter 22, Problem 148CP

### Chemistry

9th Edition
Steven S. Zumdahl
ISBN: 9781133611097

Chapter
Section

### Chemistry

9th Edition
Steven S. Zumdahl
ISBN: 9781133611097
Textbook Problem

# Consider a sample of a hydrocarbon at 0.959 atm and 298 K. Upon combusting the entire sample in oxygen, you collect a mixture of gaseous carbon dioxide and water vapor at 1.51 atm and 375 K. This mixture has a density of 1.391 g/L and occupies a volume four times as large as that of the pure hydrocarbon. Determine the molecular formula of the hydrocarbon and name it.

Interpretation Introduction

Interpretation: The molecular formula of the hydrocarbon and its name is to be stated.

Concept introduction: The molecular formula of an element defines the total number of atoms present in a molecule. The number of moles is defined as the ratio of mass with the molecular mass of an element. The mass of an element is the amount of the substance present in an element.

To determine: The name and molecular formula of the hydrocarbon.

Explanation

Explanation

Given

The pressure of the hydrocarbon sample is 0.959 atm .

The pressure after combusting the sample is 1.51 atm .

The temperature of the hydrocarbon sample is 298 K .

The temperature after combusting the sample is 375 K .

The density of the density of the mixture is 1.391 g/L .

The mixture occupies a volume four times as large as that of pure hydrocarbon.

The hydrocarbon is considered to be CxHy . The balanced chemical equation for the combustion of CxHy is,

CxHy+O2xCO2+(y2)H2O .

The initial volume of the reactants is considered to be 1 L .

The mixture occupies a volume four times as large as that of pure hydrocarbon

So, the volume of products is 4×1 L=4 L .

Mass of products is calculated by using the formula,

Mass=Density×volume .

Substitute the value of density and volume in the above formula to calculate the mass of the product.

Mass=Density×volume=1.391 g/L×4 L=5.564 g

The number of moles of reactant and product is calculated by using the expression,

Number of moles(n)=PVRT

Where,

• P is the pressure.
• V is the volume.
• R is the universal gas constant (0.0821 L atm mol1 k1) .
• T is the temperature.

For CxHy ,

Substitute the value of P, V, R and T in the above expression to calculate the moles of CxHy .

Moles(n) of CxHy=PVRT=0.959 atm×1 L0.0821 L atm mol1 K1×298 K=0.039198 mol

For product,

Substitute the value of P, V, R and T in the above expression to calculate the moles of product.

Moles(n) of product=PVRT=1.51 atm×4 L0.0821 L atm mol1 K1×375 K=0.196184 mol

According to balanced combustion equation, 1 mole of CxHy produces x moles of CO2 and y2 moles of H2O

### Still sussing out bartleby?

Check out a sample textbook solution.

See a sample solution

#### The Solution to Your Study Problems

Bartleby provides explanations to thousands of textbook problems written by our experts, many with advanced degrees!

Get Started


text:
Unscramble those case-(very)-sensitive strings

Goal

This is a simple challenge. Your goal is to unscramble a string by swapping each letter with the next letter of the same case, while leaving non-letter characters unchanged.

Step by step explanation

1. The first character is a E. We look for the next letter in upper case: it's a C. We swap these characters, which leads to CdoE!.

2. We advance to the next character: this is a d. We look for the next letter in lower case: it's a o. We swap these characters, which leads to CodE!.

3. We advance to the next character: this is the d that we've just moved here. We ignore it, because it has already been processed.

4. We advance to the next character: this is the E that was moved here at step #1. We ignore it, because it has already been processed.

5. We advance to the next character: this is a !. We ignore it, because it's not a letter.

Rules

• You can assume that the input string is made exclusively of printable ASCII characters, in the range 32 - 126.

• You may write either a full program or a function, which either prints or returns the result.

• If the input string contains an odd number of letters, the last remaining letter can't be swapped with another one and should remain in place, no matter its case. The same logic applies if the string contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters.

• This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Test cases

Input : lLEhW OroLd!
Output: hELlO WorLd!

Input : rpGOZmaimgn uplRzse naC DEoO LdGf
Output: prOGRamming puzZles anD COdE GoLf

Input : eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg
Output: tHe quICK BROWN fOx juMPS OvER THE LAzy dOg

Input : NraWgCi: Nsas-eNEiTIsev rNsiTG!!
Output: WarNiNg: Case-sENsITive sTriNG!!

Not-so-random test cases:

Input : (^_^)
Output: (^_^)

Input : AWCTY HUOS RETP

Input : hwn oeesd acsp nawyya
Output: who needs caps anyway

Input : SpMycaeIesKyBorekn
Output: MySpaceKeyIsBroken

Input : D's mroyr, Ivam. I'e faardi I act'n od htta.
Output: I'm sorry, Dave. I'm afraid I can't do that.
• I assume a similar comment holds if the input contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters. – Greg Martin Feb 4 '17 at 20:14
• This is a really clever challenge ... I also like the fact that test cases can be made by typing in a lowercase string, randomly changing some of the letters to uppercase, and then running the exact same program that solves the problem! – Greg Martin Feb 4 '17 at 20:15
• @GregMartin I found out that the problem is its own inverse because when trying a test case I accidentally typed in the output instead of the input :-) – Luis Mendo Feb 4 '17 at 20:17
• I think you should include test cases with more than one non-letter ASCII character ... I think some implementations could accidentally switch them with each other, when that's not supposed to happen. – Greg Martin Feb 4 '17 at 20:20
• The tests cases should probably include a string without uppercase letters and a string without any letters at all. – Dennis Feb 5 '17 at 2:51

Jelly, 212019 18 bytes

s2UF,
nŒlTÇyJịŒsµ⁺

Try it online!

How it works

nŒlTÇyJịŒsµ⁺  Main link. Argument: s (string)

Œl           Convert to lowercase.
n             Test for inequality.
T          Truth; yield all indices of 1's.
Ç         Call the helper link. Yields [A, B] (pair of lists).
J       Indices; yield I := [1, ..., len(s)].
y        Translate; replace the integers of I that occur in A with the
corresponding integers in B.
Œs    Swapcase; yield s with swapped case.
ị      Use the translated index list to index into s with swapped case.
µ   Combine all links to the left into a chain.
⁺   Duplicate the chain, executing it twice.

s2UF,         Helper link. Argument: J (list of indices)

s2            Split J into pairs. If the length is odd, the last list will be
a singleton list.
U           Upend; reverse each pair. This is a no-op for singletons lists.
F          Flatten, concatenating the pairs.
,          Pair the previous result with J.

Retina, 53 bytes

Not really clever, but a clean and quite readable solution

([a-z])(.*?)([a-z])
$3$2$1 ([A-Z])(.*?)([A-Z])$3$2$1

Try it online!

MATL, 22 bytes

2:"tttk<f2etAZ))P5M(Yo

How it works

2:"       % Do the following twice
ttt     %   Input string (implicit). Push three more copies
k       %   Convert to lowercase
<f      %   Indices of characters that had their code point increased by
%   the lowercase conversion, i.e. that were uppercase letters
2e      %   Convert to 2-row matrix. This pads a zero in the lower-right
%   corner if necessary
tAZ)    %   Keep only columns that don't contain zeros. Thus if there
%   was a character that can't be swapped it will be ignored
)       %   Get 2-row matrix of characters at those positions
P       %   Flip vertically. This does the swapping
5M      %   Push matrix of original indices again
(       %   Write the swapped characters onto their original positions
Yo      %   Change case. In the first iteration, this prepares the
%   string so the second iteration will process the letters that
%   were originally lowercase. In the second iteration, it
%   undoes the change of case
% End (implicit)
% Display (implicit)

Bash + Unix utilities, 77625756 54 bytes

sed -r "s/([$1)([^$1*)([$1)/\3\2\1/g"||$0 a-z]|$0 A-Z] Input in stdin. Output in stdout. (In this last version, stderr happens to be written to also, but PPCG consensus seems to be that that's OK -- stderr is simply ignored.) Edit 1: Thanks to @Dennis for 15 bytes! Improvements: (a) Taking input via stdin; (b) combining 2 sed scripts into one; and (c) replacing tr with substitution via bash parameter expansion; (b) and (c) disappeared in Edit 2. Edit 2: Shorter by 5 additional bytes. Used a function call to replace both (b) and (c) in Edit 1. Edit 3: One more byte -- passed ] as part of the function arguments. Edit 4: Replaced the two function calls with calls to the program itself when it has no arguments. Testbed and sample output: for x in 'lLEhW OroLd!' 'rpGOZmaimgn uplRzse naC DEoO LdGf' 'eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg' 'NraWgCi: Nsas-eNEiTIsev rNsiTG!!' '(^_^)' 'AWCTY HUOS RETP' 'hwn oeesd acsp nawyya' 'SpMycaeIesKyBorekn' "D's mroyr, Ivam. I'e faardi I act'n od htta."; do ./swapping <<<"$x" 2>/dev/null; done

hELlO WorLd!
prOGRamming puzZles anD COdE GoLf
tHe quICK BROWN fOx juMPS OvER THE LAzy dOg
WarNiNg: Case-sENsITive sTriNG!!
(^_^)
who needs caps anyway
MySpaceKeyIsBroken
I'm sorry, Dave. I'm afraid I can't do that.

ES6, 185 95 bytes

i=>(o=[...i]).map((c,j)=>/[a-z]/i.test(c)?o[e=c>"Z"]=1/(b=o[e])?o[o[j]=o[b],b]=c:j:0)&&o.join

Solution severely shortened with the help of @Neil, @Arnauld and @edc65

Explanation

f = i =>
// Get array of characters from input string
(o = [...i])
.map((c, j) =>
// Check if it's a text character, otherwise skip it
/[a-z]/i.test(c) ?
// Get last character position for case
// merged with setting a variable for if the character is lowercase
// merged with storing the current case character position,
// under properties on the array (with keys "true" or "false")
o[e = c>"Z"] =
// Check if there exists a character position to switch with
// merged with storing the current position for quick access
1/(b=o[e]) ?
// This statement will end up returning the Array subset,
// which will be falsy in the above conditional since (1/[])==false
o[
// Switch left character to the right
o[j]=o[b]
// Switch right character to the left
,b]=c :
// No character exists for case, so return current character position
j
// It was not a text character, so do nothing
:0
)
// Join array and return as result
&& o.join;

lLEhW OroLd!
NraWgCi: Nsas-eNEiTIsev rNsiTG!!
rpGOZmaimgn uplRzse naC DEoO LdGf
eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg
(^_^)
AWCTY HUOS RETP
hwn oeesd acsp nawyya
SpMycaeIesKyBorekn
D's mroyr, Ivam. I'e faardi I act'n od htta
.split\n
.map(testCase => console.log(f(testCase)));

• 6 bytes, the enclosing parens are redundant when we remove the second statement :) Nice. – Jan Feb 5 '17 at 15:42
• Please ignore my last comment. Here's the 99: /[a-z]/i.test(c)?o[e=c>"Z"]=1/(b=o[e])?[o[b],o[j]]=[c,o[b]]:j:0 – Arnauld Feb 5 '17 at 16:06
• [o[b],o[j]]=[c,o[b]] could be o[o[j]=o[b],b]=c – edc65 Feb 5 '17 at 17:27
• The real masterstroke here is using true and false as indexes for an array – edc65 Feb 5 '17 at 17:29
• Thanks guys, down to 95 now. It starts becoming really hard to document the solution in a way that makes sense. XD @edc65 they're stored as properties on the array object, not indexes. Yeah Arnauld figured out that they were being stored on the character array, but the reuse of the object was more of a lucky accident I think which came from a separate suggestion. Initially it was stored on a separate object which of course was completely unnecessary for the scope of the challenge. – Jan Feb 5 '17 at 18:31

Python, 82 bytes

lambda s:S(r.lower(),t,S(r,t,s))
import re
S=re.sub
r='([A-Z])(.*?)'*2
t=r'\3\2\1'

Try it online!

• how does it work? is the lambda even called? – Display Name Feb 5 '17 at 8:37
• The lambda is the actual (function) submission. Everything else is just accompanying code that has to be executed before the lambda is called. – Dennis Feb 5 '17 at 8:39

QBasic, 229 bytes

LINE INPUT s$FOR i=1TO LEN(s$)
c$=MID$(s$,i,1) IF"@"<c$AND"[">c$THEN IF u THEN MID$(s$,u,1)=c$:MID$(s$,i,1)=u$u=-i*(u=0) u$=c$ELSEIF""<c$AND"{">c$THEN IF l THEN MID$(s$,l,1)=c$:MID$(s$,i,1)=l$l=-i*(l=0) l$=c$END IF NEXT ?s$

Strategy

We loop through the input string. When we encounter an uppercase letter, we store it and its position. The second time we encounter an uppercase letter, we use those stored values to swap it with the previous one. Same for lowercase.

(I was about to post a rather longer version that used an array, because I thought that QBasic strings were immutable. Then I stumbled across the fact that MID$(strng$, index, length) = replacement$works just fine. Live and learn.) Ungolfed + commented LINE INPUT text$

FOR i = 1 TO LEN(text$) char$ = MID$(text$, i, 1)
IF "A" <= char$AND "Z" >= char$ THEN
' Uppercase
IF upperIndex = 0 THEN
' This is the first of a pair of uppercase letters
' Store the letter and its index for later
upperLetter$= char$
upperIndex = i
ELSE
' This is the second of a pair of uppercase letters
' Put it at the position of the previous uppercase letter
' and put that letter at this letter's position
MID$(text$, upperIndex, 1) = char$MID$(text$, i, 1) = upperLetter$
upperIndex = 0
END IF
ELSEIF "a" <= char$AND "z" >= char$ THEN
' Lowercase
IF lowerIndex = 0 THEN
' This is the first of a pair of lowercase letters
' Store the letter and its index for later
lowerLetter$= char$
lowerIndex = i
ELSE
' This is the second of a pair of lowercase letters
' Put it at the position of the previous lowercase letter
' and put that letter at this letter's position
MID$(text$, lowerIndex, 1) = char$MID$(text$, i, 1) = lowerLetter$
lowerIndex = 0
END IF
END IF
NEXT i

PRINT text$C++11 (GCC), 154 149 bytes #include<algorithm> [](std::string s){int*p,u,l=u=-1;for(auto&c:s)(c|32)-97<26U?p=&(c&32?u:l),~*p?(std::swap(c,s[*p]),*p=-1):*p=&c-&s[0]:0;return s;} • You should either also #include<string> or switch to C++14 and declare a generic lambda [](auto s) and assume s to be of std::string. Also, declaring [](auto&s) saves you from returning the string as modifying input arguments to serve as output is allowed. – Karl Napf Feb 13 '17 at 12:28 Qbasic, 436 408 bytes LINE INPUT a$:b=len(a$):FOR a=1TO b:t$=MID$(a$,a,1)
IF"@"<t$AND"[">t$THEN
b$=b$+"U":u$=u$+t$ELSEIF""<t$AND"{">t$THEN b$=b$+"L":l$=l$+t$
ELSE b$=b$+t$END IF:NEXT FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT FOR x=1TO b:t$=MID$(b$,x,1)
IF"U"=t$THEN u=u+1:z$=z$+MID$(g$,u,1) ELSEIF"L"=t$THEN l=l+1:z$=z$+MID$(h$,l,1)
ELSE z$=z$+t$END IF:NEXT:?z$

Saved one byte thanks to DLosc. Saved several more by changing handling of non-letter chars.

This basically consists of three parts:

• Splitting the input into 3 strings (Uppercase, Lowercase, and a map (also holding the other chars))
• Flipping the uppercase and lowercase letters
• Using the map to (re)construct the output.

A more detailed explanation (note that this is of an earlier version of the code, but the principle still applies):

' --- Part I: Reading the input
LINE INPUT a$'This FOR loop takes one character at a time b=len(a$):FOR a=1TO b
' And checks in what category the character belongs
t$=MID$(a$,a,1):SELECT CASE t$
' For each group, char t$is added to that group (u$ for uppercase,
' l$for lowercase. The map in b$ is updated with a U or L on this index,
' or with the non-letter char t$. CASE"A"TO"Z":b$=b$+"U":u$=u$+t$
CASE"a"TO"z":b$=b$+"L":l$=l$+t$CASE ELSE:b$=b$+t$
END SELECT:NEXT

' --- Part II: Swapping within case-groups
' Loop through u$and l$ twp chars at a time, and add those chunks in reverse order
' to g$and h$. Because mid$doesn't fail past the end of a string (but returns ""), ' this automatically compensates for odd-length groups. FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT ' --- Part III: Read the map to put it all back together FOR x=1TO b:t$=MID$(b$,x,1)
' See what group was in this spot, then read the next char from the flipped string.
' This keeps an index on those strings for the next lookup.
IF t$="U"THEN u=u+1:z$=z$+MID$(g$,u,1) ELSEIF t$="L"THEN l=l+1:z$=z$+MID$(h$,l,1)
' The map contains a non-letter char, just drop that in
ELSE z$=z$+t$' And finally,display the end result. END IF:NEXT:?z$

Perl 5, 48 + 1 (-p) = 49 bytes

for$p(qw/([a-z]) ([A-Z])/){s/$p(.*?)$p/$3$2$1/g}

Try it online!

PHP, 10893 83 bytes

<?=preg_replace([$a="/([a-z])([^a-z]*)([a-z])/",strtoupper($a)],"$3$2$1",$argv[1]);

Previous version (93 bytes)

<?=preg_replace(["/([a-z])([^a-z]*)([a-z])/","/([A-Z])([^A-Z]*)([A-Z])/"],"$3$2$1",$argv[1]);

Thanks to @user59178 for reminding me that preg_replace() can take arrays of strings as arguments.

$f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",
$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1])); The code is wrapped here to fit the available space. It can be executed from the command line:$ php -d error_reporting=0 -r '$f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));' 'lLEhW OroLd!' A 1-byte shorter version is possible on PHP 7 by squeezing the assignment of$f inside its first call:

echo($f=preg_replace)("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));

Both solutions, with test cases and ungolfed versions can be found on Github.

• preg_replace can take an array of replacements to do so you only need one call. In addition it's shorter to use <?= than echo. With these it's simple to get your answer down to 93 bytes. – user59178 Feb 6 '17 at 18:18
• You are right about preg_replace(). I forgot about it. I don't like <?= (in my opinion <? is not part of the language, it is just a marker) and I like to write short one-line programs that can be executed from the command line using php -r. But for the purpose of code golf you are right again. I can save 1 byte using <?=. – axiac Feb 6 '17 at 21:14

Mathematica, 96 bytes

JavaScript (ES6), 80 bytes

s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase()) This works because the only uppercase characters in the code .replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1') are A and Z, which are used to describe the character ranges. This is precisely what we need to transform into lowercase in order to process the second pass.

let f =

s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase()) console.log(f("lLEhW OroLd!")); console.log(f("rpGOZmaimgn uplRzse naC DEoO LdGf")); console.log(f("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg")); console.log(f("NraWgCi: Nsas-eNEiTIsev rNsiTG!!")); console.log(f("(^_^)")); console.log(f("AWCTY HUOS RETP")); console.log(f("hwn oeesd acsp nawyya")); console.log(f("SpMycaeIesKyBorekn")); console.log(f("D's mroyr, Ivam. I'e faardi I act'n od htta.")); • Actually, it turns out to be very similar to this Python answer by Dennis. – Arnauld Feb 5 '17 at 19:34 ES6 155 - 195 bytes I know there's already a better answer, but I wanted to try without regex. This one works on punctuation too, but that seems to violate the (^_^) test. In that case I have another c() function, given below. f=(s)=>{d={};s=[...s];for(i in s){b=s[i];for(j in s)if(i<j&!d[i]&c(s[j])==c(b)){d[j]=1;s[i]=s[j];s[j]=b;break}}return s.join('')} c=c=>~(c.charCodeAt()/32) f("M I'o DaG") //> I'M a GoD f("(^_^)") //> )_^^( c=c=>((c!=c.toUpperCase())<<1|c!=c.toLowerCase())||c.charCodeAt() f("M I'o DaG") //> I'M a GoD f("(^_^)") //> (^_^) Explanation f=(s)=>{ d={}; //list of indexes already swapped s=[...s]; //string to array, stolen from above ES6 answer for(i in s){ b=s[i]; //keep a note of what we are swapping for(j in s) //iterate over the array again if( i<j & !d[i] & c(s[j])==c(b) ){ //only pay attention after we pass i'th //only swap if this char hasn't been swapped //only swap if both chars in same 'category' d[j]=1; //note that the latter char has been swapped s[i]=s[j]; s[j]=b; break //avoid swapping on the same 'i' twice } } return s.join('') //return as string } Perl 6, 56 bytes {for "A".."Z","a".."z" ->@c {s:g/(@c)(.*?)(@c)/$2$1$0/}}

Takes a string variable as an argument, and modifies it in-place so that after calling the lambda the variable contains the result.

Longer than it would be in Perl, because:

• The new regex syntax is more verbose, e.g. writing out the character classes would look like <[A..Z]> instead of [A-Z].
• Regexes are first-class source code parsed at compile time, and a string can only be interpolated into them at run-time if it consists of a self-contained subregex (i.e. you can't interpolate a string into a character class).
• Explict EVAL, which would allow more flexibility, requires the golf-unfriendly use MONKEY-SEE-NO-EVAL; pragma.

On the plus side, an array in a @ variable can be referenced directly in a regex, and is treated as an alternation.

{reduce ->$_,@c {S:g/(@c)(.*?)(@c)/$2$1$0/},$_,"A".."Z","a".."z"} Functional version (outputs the result as the return value of the lambda). R, 343 Bytes Terribly clumsy R solution: f <- function(x) { y=unlist(strsplit(x,"")) z=data.frame(l=ifelse(y %in% letters,0,ifelse(y %in% LETTERS,1,2)),s=y) l <- list(which(z$l==0),which(z$l==1)) v <- unlist(l) for(j in 1:2) for (i in seq(1,ifelse(length(l[[j]])%%2==1,length(l[[j]])-2,length(l[[j]])-1),2)) l[[j]][i:(i+1)] <- rev(l[[j]][i:(i+1)]) z[v,] <- z[unlist(l),] return(z$s)
}

f("D's mroyr, Ivam. I'e faardi I act'n od htta.")

# [1] I ' m   s o r r y ,   D a v e .   I ' m   a f r a i d   I   c a n ' t   d o   t h a t .

Python 2, 181 bytes

Much longer than it should be but anyway:

def F(s):
for l in[i for i,c in enumerate(s)if c.isupper()],[i for i,c in enumerate(s)if c.islower()]:
for a,b in zip(l[0::2],l[1::2]):s=s[:a]+s[b]+s[a+1:b]+s[a]+s[b+1:]
print s

This first creates two lists: one of the indices of the uppercase characters and one for the lowercase characters. Each of these lists is looped through in pairs of indices, and the characters at those indices are switched.

I'll golf this down tomorrow, but for now it's time to sleep.

Pip, 28 bytes

Y[XLXU]aRy..*?.y{Sa@0a@va}

Takes input as a command-line argument. Try it online!

Explanation

This is a regex solution, using the builtin regex variables XL (lowercase letters, [a-z]) and XU (uppercase letters, [A-Z]).

a is 1st cmdline arg; v is -1 (implicit)
Y[XLXU]                       Yank a list containing XL and XU into y
y..*?.y            Concatenate y, .*?, and y itemwise, giving this list:
[[a-z].*?[a-z]; [A-Z].*?[A-Z]]
aR                     In a, replace matches of each regex in that list...
{        }  ... using this callback function:
Sa@0a@v     Swap the 0th and -1st characters of the match
a    and return the resulting string
Print (implicit)

When the second argument to R is a list, the replacements are performed in series; thus, the lowercase replacement and the uppercase replacement don't interfere with each other.

AWK, 121 129 bytes

BEGIN{FS=OFS=""}{for(a=1;a<=NF;a++){if($a~/[A-Z]/?U>0?p=U+(U=0):0*(U=a):$a~/[a-z]/?L>0?p=L+(L=0):0*(L=a):0>0){t=$a;$a=$p;$p=t}}}1

Try it online! Note: Link has 8 extra bytes to allow multiline input

Usage is fairly typical, but does require a version of AWK that accepts an empty string as the field separator (most versions of gawk but I'm pretty sure the original AWK would fail :( )

It's very straightforward as it simply iterates over each character and checks if it's found one of that case before. If so, it swaps the characters and resets the checked index. On the learning side of things, I'd never used an assignment statement within an assignment statement in AWK before. For some reason it had never come up. :)

I might be able to shave a couple of bytes by saying to assign OFS and FS outside a BEGIN block via command-line assignment or similar, but it's "cleaner" this way.

Adding the TIO link showed me that I had a transcription error that required 8 bytes to fix :( (I left out 0*(U=a):)

Stax, 18 bytes

âß:}\]ó☺æ■jφ╛jz/Φi

Run and debug it

The general approach is regex-based.

• Two times do:
• Find all matches for [a-z].*?[a-z].
• Swap the first and last character in matches.
• Invert case.

R, 223163 bytes 148 bytes

EDIT: -60 bytes by implementing a for loop

EDIT: -15 bytes from Giuseppe

u=utf8ToInt(scan(,''));for(i in c(65,97)){l=which(u%in%i:(i+25));x=sum(l|1)%/%2;u[l[1:(x*2)]]=u[c(matrix(l,2)[2:1,1:x])]};cat(intToUtf8(u,T),sep="")

Try it online!

Works by testing if character is a lowercase or uppercase, places them in a matrix, inverts the matrix to extract the values in a swapped format. Then output with cat. Try it online struggles with scan(,'') if the code is more than one line, hence the semicolons throughout the single line of code.

• I get 168 on your link, but this golf is 163 – Giuseppe Aug 7 '19 at 21:28
• And this brings it to 162. – Giuseppe Aug 7 '19 at 21:30
• this probably works; the x fiddling is the clever bit, but getting rid of m=matrix was 4 bytes as well. – Giuseppe Aug 7 '19 at 21:37
• What about the scan(,'') problem? And reducing the "lLEhW OroLd!" in TIO to scan(,'') or some other way to get input? – Sumner18 Aug 7 '19 at 21:39
• You missed a couple: tio.run/##Dc5NC4IwGADgv2LC8H1rEA76muzYIRC6GB3Eg6zEwdxibjSofvvy/… – Giuseppe Aug 7 '19 at 22:17

C (gcc), 212206205 203 bytes

• Thanks to ceilingcat for golfing six seven nine bytes.
#define I(a,b)if(S[j=i]/a&b/S[i]){for(;S[++j]<a|S[j]>b;);j<l?s[i]=S[j],s[j]=S[i]:0;}
i,j,l;f(char*S){char*s=calloc(l=-~strlen(S),1);for(i=~0;++i<strlen(S);)if(!s[i]){s[i]=S[i];I(65,90)I(97,'z')}puts(s);}

Try it online!

• @ceilingcat Thank you. – Jonathan Frech Aug 6 '19 at 20:05
• @ceilingcat Thank you. – Jonathan Frech Jun 13 '20 at 23:11
• @ceilingcat Thank you. – Jonathan Frech Jun 17 '20 at 21:33

05AB1E, 26 23 bytes

2FÐlø€Ë≠āsƶ0KD2ôí˜‡<è.š

I/O as a list of characters.

Explanation:

2F                # Loop 2 times:
Ð               #  Triplicate the current character-list
#  (which will use the implicit input-list in the first iteration)
l              #  Lowercase all letters of the top copy
ø             #  Zip/transpose the top two lists; pairing them together, and swapping
#  rows/columns
€Ë≠          #  Check for each pair whether they're NOT the same
#  (so uppercase characters that have now become lowercase)
ā               #  Push a list in the range [1, length] (without popping)
s              #  Swap so the mapped list is at the top again
ƶ             #  Multiply each 1/0 by its 1-based index
0K           #  Remove all 0s
D          #  Duplicate this list of 1-based indices
2ô        #  Split it into parts of size 2
í       #  Reverse each part
˜      #  Flatten the list of swapped indices
‡     #  Transliterate the indices with the swapped indices in [1, length]
<    #  Decrease each by 1 (because 05AB1E uses 0-based indexing)
è   #  Index them into the current character-list
.š #  And swap all cases (lowercase to uppercase, and vice-versa)
# (after the loop, the resulting character-list is output implicitly)

Java 7, 117 bytes

String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);} EDIT: Just noticed I have a similar answer as @Leo's Retina answer, even though I've thought about it independently.. Ungolfed: String c(final String s) { String x = "([a-z])(.*?)([a-z])", y = "$3$2$1";
return s.replaceAll(x, y).replaceAll(x.toUpperCase(), y);
}

Test code:

Try it here.

class M{
static String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2\$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);}

public static void main(String[] a){
System.out.println(c("lLEhW OroLd!"));
System.out.println(c("rpGOZmaimgn uplRzse naC DEoO LdGf"));
System.out.println(c("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg"));
System.out.println(c("NraWgCi: Nsas-eNEiTIsev rNsiTG!!"));
System.out.println(c("(^_^)"));
System.out.println(c("AWCTY HUOS RETP"));
System.out.println(c("hwn oeesd acsp nawyya"));
System.out.println(c("SpMycaeIesKyBorekn"));
System.out.println(c("D's mroyr, Ivam. I'e faardi I act'n od htta."));
}
}

Output:

hELlO WorLd!
prOGRamming puzZles anD COdE GoLf
tHe quICK BROWN fOx juMPS OvER THE LAzy dOg
WarNiNg: Case-sENsITive sTriNG!!
(^_^)