text:
# Matplotlib Confidence Interval

Much of that. Setting to None will skip bootstrapping. For example, a 95% likelihood of classification accuracy between 70% and 75%. There are two types of supervised machine learning algorithms: Regression and classification. "Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. The notched boxplot allows you to evaluate confidence intervals (by default 95% confidence interval) for the medians of each boxplot. The pstdev is used when the data represents the whole population. py # Vog, 31 okt 2011 #----- import numpy from matplotlib. When standard deviation errors bars overlap even less, it's a clue that the difference is probably not statistically significant. Regression Analysis / Linear Regression. boxplot(df['A'],notch= True); Plotting boxplot using seaborn. Let me know if there is anything wrong. For instance, predicting the price of a house in dollars is a regression problem whereas predicting whether a tumor is malignant or benign is a classification problem. Meanwhile, in matplotlib you actually have to create a new dataset with your means (and standard deviations if you want confidence intervals). lower is the lower band of the confidence interval. A dictionary mapping each component of the boxplot to a list of the matplotlib. set_ticks_position('bottom') ax. That dictionary has the following keys (assuming vertical boxplots): boxes: the main body of the boxplot showing the quartiles and the median’s confidence intervals if enabled. 57( q 3 – q 1 )/sqrt( n ) , where q 2 is the median (50th percentile), q 1 and q 3 are the 25th and 75th percentiles, respectively, and n is the. Linear Regression II: Categorical variables, modeling nonlinearity (transformation, interaction). use('agg') import matplotlib. Results and discussion 3. The Fisher-Behrens problem is the determination of a test for the equality of means for two normal distributions with different variances. Select Anaconda Prompt from the Windows Start Menu. pyplot as plt plt. Matplotlib also won't accept categorical variables as the variable for the x-axis, so you have to first make the bar chart with numbers as the x-axis, then change the tick-marks on the x-axis back to. randn(n) plt. Figure 3: Setting the aspect ratio to be equal and zooming in on the contour plot. The 95% confidence interval is a range of values that you can be 95% certain contains the true mean of the population. randn(n) y = np. This was my line in Matlab Pbci = bootci(2000,{@mean,Pb},'alpha',. Homework 1 Solution. 718281, and is the base of the natural logarithm, ln (this means that, if , then. boxplot function. LME 모델에서 신뢰 구간 추출. 66 Model | 2339. pyplot as plt ## initialize the axes fig = plt. bar A scatter plot can suggest various kinds of correlations between variables with a certain confidence interval. Sets the positions of the boxes. “sd” means to draw the standard deviation of the data. The width of a confidence interval estimate for a proportion will be: a. That dictionary has the following keys (assuming vertical boxplots): boxes: the main body of the boxplot showing the quartiles and the median’s confidence intervals if enabled. $\begingroup$ Usually confidence intervals refer directly to population parameters (such as mean $\mu,$ median $\eta,$ or standard deviation $\sigma$), rather than to graphical summaries of data (such as histograms and boxplots). The confidence intervals for the forecasts are (1 - alpha)% plot_insample bool, optional. This data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. Matplotlib also won't accept categorical variables as the variable for the x-axis, so you have to first make the bar chart with numbers as the x-axis, then change the tick-marks on the x-axis back to your original categories. pyplot as plt import numpy as np import random # prints Happiness Rank Happiness Score Lower Confidence Interval \ count 157. The dashed line is 99% confidence band. gnuplot_i_examples, programs which demonstrate the use of the gnuplot_i library for interactive runtime gnuplot graphics. def getVar (portfolio, c): #portfolio dataframe, confidence interval P = 15000 #each position % of portfolio, should create a new one to store marketvalue of each position to be more precise #c = 0. Cite 8th Apr, 2020. Suppose our 95% confidence interval for the true population mean height of a species of plant is: 95% confidence interval = (16. " When reporting confidence intervals, use the format 95% CI [LL, UL] where LL is the lower limit of the confidence interval and UL is the upper limit. The confidence intervals do not overlap, but the P value is high (0. Kite is a free autocomplete for Python developers. 3250081500000022) The M observed is 0. maxlog float, optional. Creating a competing risks model¶. upper is the upper band of the confidence interval. array([1,2,3,4]) #(Means of your data) data_df=np. 1)%90 confidence interval. Compute quantile regression lines. A dictionary mapping each component of the boxplot to a list of the matplotlib. And here is an example where the rule of thumb about SE is not true (and sample sizes are very different). scatter The confidence interval extends from the 2. The quality of the fit should always be checked in these cases. This interval is such that the crystallite is small enough to not be affected by finite-size effects, but large enough to give the system time to equilibrate into a steady-state growth condition. Homework 1 Solution. To create the notch, set notch=True in the plt. It is well supported in a wide range of environments such as web application servers, graphical user interface toolkits, Jupiter notebook and iPython notebook, iPython shell. Confidence-Interval – вопросы и ответы 54. 5 y = amp * np. interval method, to get the size of confidence interval, you just need the. , & Konig, A. pyplot as plt. Of course deriving confidence intervals around your data (using standard deviation) or the mean (using standard error) requires your data to be normally distributed. sqrt ( 2 * np. spines['right']. In Proceedings of the SIGCHI Conference on Human Factors in Computing Systems (pp. 042] contains the true population mean. Note: st is from the import command import scipy. 5 %, so you can use 2 * std to estimate the 95 % interval:. geom_smooth allows to add the result of a model to your scatterplot, with confidence interval as well. So, in the above example, we can state that the confidence interval for the effectiveness of the said test in the population is [0,3/200] = [0,1/67]. The confidence interval has an associated confidence level that quantifies the level of confidence that the deterministic parameter is captured by the interval. The ODS OUTPUT statement creates a data set from a table that contains the mean differences between pairs of groups, along with 95% confidence intervals for the differences. print (__doc__) # Code source: Jaques Grobler # License: BSD 3 clause import matplotlib. Distributions is the Competing_Risks_Model. errorbar([0,1,2,3], data_m. fftconvolve (in1, in2, mode='full') [source] ¶ Convolve two N-dimensional arrays using FFT. When standard deviation errors bars overlap even less, it's a clue that the difference is probably not statistically significant. Solution: You can write:. This interval is defined so that there is a specified probability that a value lies within it. png file mpl. T # Data for. Linear Regression II: Categorical variables, modeling nonlinearity (transformation, interaction). References. Python Practice: Linear regression with statsmodels II. {scatter,line}_kws dictionaries. Which of the following methods from Python’s scipy. NORM Function in Excel returns the value that you can use to construct the confidence interval for a population mean. To see how well-calibrated the model is, we can check the coverage of the 95% confidence interval (the percentage of y values from the validation dataset falling within our 95% predictive interval). import matplotlib. 88 $\rightarrow$ (12. In the following example, we will use multiple linear regression to predict the stock index price (i. Parameters. How to Interpret Confidence Intervals. The location (loc) keyword specifies the mean. We'll also discuss types of errors, and what they mean in practice. The horizontal lines displayed in the plot correspond to 95% and 99% confidence bands. Bayesian optimization runs for 10 iterations. dependence = the function uses a function q(p) which is an inverse cdf of normal distribution ##### the function takes in 3 arguments as: precision = d population probability = p z_level that is set to 95% confidence interval but can be changed to any confidence value. bar() and ax. medians: horizontal lines at the median of each box. import numpy as np import scipy. Identity (do nothing) statistic. This paper presents EinsteinPy (version 0. Robustness of Efficiency: confidence intervals hold true for non normal tails. Example 1: Create a chart of the 95% confidence and prediction intervals for Example 1 of the Confidence and Prediction Intervals (whose data is duplicated in columns A and B of Figure 1). 5 %, so you can use 2 * std to estimate the 95 % interval:. a confidence interval of about 10% of the mean value at a confidence level of 90-95% is often considered import matplotlib. stats as ss data_m=np. If bootstrap is None, no bootstrapping is performed, and notches are calculated using a Gaussian-based asymptotic approximation (see McGill, R. Closed sty1882 opened this issue Jan 29, 2016 · 6 comments You might have more luck asking on Stackoverflow with the seaborn and matplotlib tags. CI stands for confidence interval. We now show how to create charts of the confidence and prediction intervals for a linear regression model. As much as I'd like to drop a confidence interval on how likely these measurements are to be the same, it seems I am unable to find a strategy which is accepted. Results were presented as odds ratio with corresponding 95% confidence interval (CI). Search for: Tags. t関数が使用できるようになります。 =confidence. We need to first determine what the new confidence coefficient is. Pyplot is the core object that contains the methods to create all sorts of charts and features in a plot. (y_label)>0: # Plot the function, the prediction and the 95% confidence interval based on. IMPORTING MATPLOTLIB. matplotlib will now display a RuntimeWarning when too many figures have been opened at once. We can write this in a linear algebra form as: T*p = Ca where T is a matrix of columns [1 t t^2 t^3 t^4], and p is a column vector of the fitting parameters. 075367449999995, 1. Jupyter Nootbooks to write code and other findings. spines['right']. Box-Cox power transformed array. std) As a quick note, the black line that you see crossing through the top of each data bar is actually the confidence interval for that data, with the default being the 95% confidence interval. Example 1: Create a chart of the 95% confidence and prediction intervals for Example 1 of the Confidence and Prediction Intervals (whose data is duplicated in columns A and B of Figure 1). Cite 8th Apr, 2020. Within reliability. I want a confidence interval for the line. test dataset 72. py # Vog, 31 okt 2011 #----- import numpy from matplotlib. statistical hypothesis 78. 38077 1 2339. This interval is defined so that there is a specified probability that a value lies within it. We can write this in a linear algebra form as: T*p = Ca where T is a matrix of columns [1 t t^2 t^3 t^4], and p is a column vector of the fitting parameters. set_ticks_position('bottom') ax. pyplot as plt. It should pass all the automated tests. t関数が使用できるようになります。 =confidence. Parameters. CONFIDENCE. , 1978, and Kendall and Stuart, 1967). medians: horizontal lines at the median of each box. " Native Matplotlib is the cause of frustration to many data analysts due to the complex syntax. Matplotlib legends for mean and confidence interval plots When plotting means and confidence intervals, sometimes the mean lines are hard to see and it’s nice to have included in your legend the color of the confidence interval shading. 039, n=9972 for ρ*=0. plotting in Python (3. Menu and widgets. Apr-11-2017, 08:58 AM. std) As a quick note, the black line that you see crossing through the top of each data bar is actually the confidence interval for that data, with the default being the 95% confidence interval. Line2D instances created. bootstrapped provides pivotal (aka empirical) based confidence intervals based on bootstrap re-sampling with replacement. Distributions is the Mixture_Model. import numpy as np import scipy. CDF-based nonparametric confidence interval Metadata This file contains additional information such as Exif metadata which may have been added by the digital camera, scanner, or software program used to create or digitize it. as The level gets higher, the interval is also get higher. Identity (do nothing) statistic. Pandas for data manipulation and matplotlib, well, for plotting graphs. Matplotlib also won't accept categorical variables as the variable for the x-axis, so you have to first make the bar chart with numbers as the x-axis, then change the tick-marks on the x-axis back to your original categories. 96 multiplied by standard deviation divided by delta the whole square. array([5,6,7,8]) #(Degree-of-freedoms of your data) data_sd=np. /32 Confidence intervals (1) We usually approximate the mean of our distribution using the samples we have. n_boot int, optional Number of bootstrap resamples used to estimate the ci. Matplotlib is the “grandfather” library of data visualization with Python. patches import Polygon def confpred_band(x, dfdp, prob, fitobj, f, prediction, abswei=False, err=None): #----- # Return values for a confidence or a. narrower when the sample proportion if 0. pyplot as plt plt. spines['right']. std(y)/np. The dashed line is 99% confidence band. Default = 0. ★ Generated confidence intervals by normality based interval, exact interval, score interval, parametric raw percentile interval and parametric bootstrap t-interval. """ DS GA 1002 Homework 4 Problem 2 """ import os. medians: horizontal lines at the median of each box. Calculate normal confidence interval ellipse. 14, specificity of 100, precision of 100, and F1 score of 99. In this video I show you how to add error bars to a chart using matplotlib in python and the various options that are available. 0, new plotting functions including relplot() are released. pyplot as plt plt. Visualizing Confidence Intervals This post is about visualizing confidence intervals. wider for a sample size of 100 than for a sample size of 50. variable 77. Kite is a free autocomplete for Python developers. Import Matplotlib and use the errorbar() function from Matplotlib. This is a common way to actually present your confidence interval. "Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Complete hands-on exercises and follow short videos from expert instructors. 0 * x #some confidence interval ci = 1. figure() ax = plt. errorbar([0,1,2,3], data_m. Browse other questions tagged macos python3 matplotlib or ask your own question. If time series is non-random then one or more of the autocorrelations will be significantly non-zero. The software plots the PDF and the region that corresponds to a defined confidence limit (the confidence limit used here is always equal to 95%), using the matplotlib Python module. data samples 80. In the following example, we will use multiple linear regression to predict the stock index price (i. norm (* args, ** kwds) = [source] ¶ A normal continuous random variable. Creating a competing risks model¶. patches import Polygon def confpred_band(x, dfdp, prob, fitobj, f, prediction, abswei=False, err=None): #----- # Return values for a confidence or a. However, graphical summaries can sometimes show confidence intervals of parameters. A dictionary mapping each component of the boxplot to a list of the matplotlib. See installing Anaconda on Windows for installation instructions. Much of that. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing. An interval plot shows a 95% confidence interval for the mean of each group. 99 #confidence interval, moved to function totalrisk = 0 for i in portfolio: rets = portfolio[i]. 3) with Seaborn (0. Python Practice: Linear regression with statsmodels II. Statistical packages will usually provide both the p-values and the confidence intervals at 95% confidence level (which is a 5% significance level). The 69% confidence interval, z, of a Gaussian distribution is given by: z = s q r t ( 2 ) * e r f - 1 ( 0. So right now, on the curve, you’re going to set a threshold of about 0. LME 모델에서 신뢰 구간 추출. 0, new plotting functions including relplot() are released. n_boot int, optional. It has great documentation that is filled with tutorials and produces really nice-looking plots. , Fisher, D. pyplot as plt plt. randint(1, 10, 30) y. load_diabetes (return_X_y = True) # Use only one feature. All confidence intervals are of the form “point estimate” plus/minus the “margin of error”. import matplotlib. Increase the confidence level, will increase the range of the interval as well. The most complex part of interpreting a statistical histogram is to get a handle on what you want to show on the x and y axes. matplotlib version 2. While the MAD does have robustness of validity, it is affected by non normal tails, and so doesn’t have robustness of efficiency. This helps in achieving. interpret 80. use('agg') import matplotlib. We’ve used Plotly’s fill to option to show the confidence intervals. Calculate normal confidence interval ellipse. 36 months so our steps will be 36 and for a confidence interval of 95% we will pass the alpha value as 0. for 95% of true-y to be within our predicted 95% confidence band on out of sample data), I expect we’d want to base the interval bounds on the ssr of the y/yhat for some validation data set held out from training. Import Matplotlib and use the errorbar() function from Matplotlib. We need to first determine what the new confidence coefficient is. {scatter,line}_kws dictionaries. Dotted blue lines are the two. The confidence intervals for the forecasts are (1 - alpha)% plot_insample bool, optional. In this case, bootstrapping the confidence intervals is a much more accurate method of determining the 95% confidence interval around your experiment’s mean performance. You don't need. While the MAD does have robustness of validity, it is affected by non normal tails, and so doesn’t have robustness of efficiency. stat_qq_line. The confidence interval is estimated using a bootstrap; for large datasets, it may be advisable to avoid that computation by setting this parameter to None. Plotting confidence intervals of linear regression in Python. CONFIDENCE. Posterior confidence intervals. a confidence interval of about 10% of the mean value at a confidence level of 90-95% is often considered import matplotlib. For example, a 95% likelihood of classification accuracy between 70% and 75%. figsize : tuple Figsize in inches dpi : int Resolution of the figure in dots per inches. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing. randint(1, 10, 30) y. They are different from confidence intervals that instead seek to quantify the uncertainty in a population parameter such as a mean or standard deviation. A 2-tailed P value of <. , 1978, and Kendall and Stuart, 1967). 409961 3 1 0. Python Practice: Linear regression with statsmodels II. The confidence intervals do not overlap, but the P value is high (0. To produce confidence intervals which we expect to line up well with predictions on out-of-sample data (i. pyplot as plt plt. I've attached some images, along with the python script I used to generate them. The confidence interval is estimated using a bootstrap; for large datasets, it may be advisable to avoid that computation by setting this parameter to None. calibration. Bayesian optimization runs for 10 iterations. ★ Generated confidence intervals by normality based interval, exact interval, score interval, parametric raw percentile interval and parametric bootstrap t-interval. import matplotlib. 69 ) The spacing, s , of adjacent intervals of mean, μ , is given by:. Matplotlib is the “grandfather” library of data visualization with Python. Choose from 330+ interactive courses. stat_qq_line. If time series is random, such autocorrelations should be near zero for any and all time-lag separations. Note: The confidence interval relates to the location of the regression line. Random preview Confidence interval for a GARCH model with R[Time Series problem]. The Fisher-Behrens problem is the determination of a test for the equality of means for two normal distributions with different variances. Regression Analysis / Linear Regression. ci – Confidence interval for which to compute the upper and lower bounds. 57( q 3 – q 1 )/sqrt( n ) and q 2 + 1. Line2D instances created. We now show how to create charts of the confidence and prediction intervals for a linear regression model. Non Normal Distributions. The location (loc) keyword specifies the mean. Sample size for continuous data can be calculated by n is equal to 1. Having good descriptive labels on the axes will help. As we have seen, confidence intervals for the estimated parameters, or for the mean response, can be computed for any sample size $$N > 2$$ and any confidence level $$0 \leq \alpha \leq 1$$. Post a Review. 34, sensitivity of 98. T Function in Excel: CONFIDENCE. ci : Confidence Interval (신뢰구간) sd : sample standard deviation (표본표준편차) 로 95% 신뢰구간을 나타낸다. Here the number “2” is the confidence coefficient, and the number “95. mean); Fitting different kinds of models. import numpy as np import scipy. 95 => a = 0. A confidence interval for a mean is a range of values that is likely to contain a population mean with a certain level of confidence. The irrational number e is also known as Euler’s number. An interval plot shows a 95% confidence interval for the mean of each group. (If using OSX or Linux, the terminal could also be used). Parameters: alpha (float, optional (default=0. In the following example, we will use multiple linear regression to predict the stock index price (i. References. Confidence Intervals. If you are looking for a simple linear regression fit, you can use directly either lmplot or regplot from seaborn. reg wage tenure Source | SS df MS Number of obs = 2231-----+----- F( 1, 2229) = 72. CONFIDENCE. confidence interval 80. Line2D instances created. (y_label)>0: # Plot the function, the prediction and the 95% confidence interval based on. Increase the confidence level, will increase the range of the interval as well. 954025 1 3 0. Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. Most well known is Matplotlib. Closed sty1882 opened this issue Jan 29, 2016 · 6 comments You might have more luck asking on Stackoverflow with the seaborn and matplotlib tags. pyplot as plt #create some random data np. We will now look at different techniques for predicting the number of passengers for the next 10 years (By default Python, predicts values for ten years). Meanwhile, in matplotlib you actually have to create a new dataset with your means (and standard deviations if you want confidence intervals). A robust way to calculate confidence intervals for machine learning algorithms is to use the bootstrap. The percentile method is also available. std) As a quick note, the black line that you see crossing through the top of each data bar is actually the confidence interval for that data, with the default being the 95% confidence interval. stat_function. narrower for 90% confidence than for 95% confidence. confidence : float If not None, plot the specified percentage confidence interval on the mean and limits of agreement. The dashed line is 99% confidence band. Box-Cox power transformed array. In this course, Matplotlib for Data Visualization and Python: Getting Started, you’ll learn the foundations of Matplotlib to reveal the story behind the data. array([5,6,7,8]) #(Degree-of-freedoms of your data) data_sd=np. Let me know if there is anything wrong. The plt is used as an alias name for Matplotlib and will be used in the rest of the coding example in this blog. The first step is to import the python libraries that we will use. norm¶ scipy. It should pass all the automated tests. 3250081500000022) The M observed is 0. Let's say we want a printout of our confidence interval for an entire sample (Note, if you're looking for a visual of a confidence interval over time, check out the post here!) The solution here requires Periscope Data's Python/R Integration as we'll be using Python's Scipy package and matplotlib text charts. The individual scattered observations are survey data (actual average number of cars, actual average size of dwellings, for groups of around 120 dwellings), so these are fixed. Statistical analysis was performed using SPSS v 24. Suppose our 95% confidence interval for the true population mean height of a species of plant is: 95% confidence interval = (16. Seaborn regplot Without Regression Line. I think this fixes the end cap addition to barplot and scatterplot confidence intervals. 96 multiplied by standard deviation divided by delta the whole square. The two graphs below summarize BMI (Body Mass Index) measurements in four categories, i. python code examples for matplotlib. In the other words, it is a range of values we are fairly sure our true value lies in. Line2D instances created. , the dependent variable) of a fictitious economy by using 2 independent/input variables:. Distributions module (available distributions are Exponential, Weibull, Normal, Lognormal, Gamma, Beta). Results and discussion 3. Prepare to dive deeper into crucial concepts regarding experiments and testing by reviewing confidence intervals, hypothesis testing, multiple tests, and the role that power and sample size play. Preoperative variables that correlated with ER were included to generate nomogram and decision trees. 57( q 3 – q 1 )/sqrt( n ) , where q 2 is the median (50th percentile), q 1 and q 3 are the 25th and 75th percentiles, respectively, and n is the. medians: horizontal lines at the median of each box. A dictionary mapping each component of the boxplot to a list of the matplotlib. pyplot import figure, show, rc from kapteyn import kmpfit from matplotlib. seed(0) x = np. stats as st. Line2D instances created. You don't need. Getting into the statistics of standard deviations and confidence intervals is beyond the scope of this visualization focused article (you're welcome), but I do want to leave you with a sense of how to do this from a matplotlib prospective. The scale (scale) keyword specifies the standard deviation. Jupyter notebooks is kind of diary for data analysis and scientists, a web based platform where you can mix Python, html and Markdown to explain your data insights. , and Larsen, W. To produce confidence intervals which we expect to line up well with predictions on out-of-sample data (i. pyplot as plt %matplotlib inline. A 2-tailed P value of <. This tutorial is designed to help you get started creating visuals with Python in Power BI Desktop. 2020-05-21 python matplotlib plot confidence-interval. In seaborn version 0. Pandas ewma Pandas ewma. Bootstrapping is an option to derive confidence intervals in cases when you are doubting the normality of your data. 01 spacing from -2 to 10. For real input, exp(x) is always positive. When plotting means and confidence intervals, sometimes the mean lines are hard to see and it's nice to have included in your legend the color of the confidence interval shading. array([1,2,3,4]) #(Means of your data) data_df=np. This script calculates and plots confidence intervals around a linear regression based on new observations. lmplot(x="size", y="tip", data=tips, x_estimator=np. narrower for 90% confidence than for 95% confidence. 5 %, so you can use 2 * std to estimate the 95 % interval:. upper is the upper band of the confidence interval. from vega_datasets import data # Let's use the jobs dataset for this since # it has two dimensions we can compare across: # job type and gender. barh() A simple bar chart. 50 than when the sample proportion is 0. Returns fig Figure. 58 standard deviation. This tutorial is designed to help you get started creating visuals with Python in Power BI Desktop. This helps in achieving. So, for simplicity’s sake, let’s pretend that you hired a terrible accountant. Chebyshev's Theorem. That dictionary has the following keys (assuming vertical boxplots): boxes: the main body of the boxplot showing the quartiles and the median's confidence intervals if enabled. See installing Anaconda on Windows for installation instructions. Then, the value of Xis determined based on where the number generated from uniform distribution fell. The first way to plot a confidence interval is by using the lineplot() function, which connects all of the data points in a dataset with a line and displays a confidence band around each point: import numpy as np import seaborn as sns import matplotlib. This page provides Python code examples for matplotlib. Import the libraries and specify the type of the output file. Preoperative variables that correlated with ER were included to generate nomogram and decision trees. (Coin Toss Simulation) Write codes to simulate tossing a fair coin to see how the law of large numbers works. Using 2 * std to estimate the 95 % interval In a normal distribution, the interval [μ - 2σ, μ + 2σ] covers 95. stats as st. Matplotlib is the most widely used visualization tools in python. Figure 3: Setting the aspect ratio to be equal and zooming in on the contour plot. Inverse Propensity Weighting Dealing with Selection Bias By Propensity Based Feature Selection. fftconvolve¶ forestci. Returns fig Figure. 3) with Seaborn (0. The way to interpret confidence intervals is that if we were to repeat the above process many times (including collecting a sample, then generating a bunch of “bootstrap” samples from the big sample, then taking the percentiles of these sample means), then 95% of the time, our interval would contain the “true” mean of the data. bar() and ax. as The level gets higher, the interval is also get higher. 88 $\rightarrow$ (12. Note: The confidence interval relates to the location of the regression line. Notched Boxplot in matplotlib. After I couldn't find anything…. Using base R Base R is also a good option to build a scatterplot, using the plot() function. Number of bootstraps to use for computing the confidence interval. 38077 1 2339. The first axes (accessible with FigName. The Fisher-Behrens problem is the determination of a test for the equality of means for two normal distributions with different variances. import pandas as pd import matplotlib. The normal distribution function gives the probability that a standard normal variate assumes a value in the interval ,. mean); Fitting different kinds of models. Creating an Dynamically-Colored Visual with Matplotlib This project inspired by the following paper: Ferreira, N. A boxplot, sometimes called a box and whisker plot, is a type of graph used to display patterns of quantitative data. As pointed by Rothman (2016) and the American Statistical Association, relying on p-values forces a false dichotomy between results that are significant and those that are non-significant. wider for a sample size of 100 than for a sample size of 50. More people will see it that way. Specifies whether to bootstrap the confidence intervals around the median for notched boxplots. The plotted Figure instance. This is easy to interpret, but the viewer cannot see that the data is actually quite skewed. /32 Confidence intervals (1) We usually approximate the mean of our distribution using the samples we have. add_subplot (111) ## format axes ax. norm (* args, ** kwds) = [source] ¶ A normal continuous random variable. 1) The closest thing to R’s ggplot2 that I have been able to find for Python is Seaborn, which is based on matplotlib. pyplot as plt plt. Where t is the value of the Student???s t-distribution for a specific alpha. Distributions module (available distributions are Exponential, Weibull, Normal, Lognormal, Gamma, Beta). Having good descriptive labels on the axes will help. , 1978, and Kendall and Stuart, 1967). Frequently, 95% is chosen for the confidence level and other purposes in statistics, although 90% and 99% are also common; the higher the confidence level, the wider the interval. The horizontal lines displayed in the plot correspond to 95% and 99% confidence bands. We can write this in a linear algebra form as: T*p = Ca where T is a matrix of columns [1 t t^2 t^3 t^4], and p is a column vector of the fitting parameters. Existing axes to plot with. Import the libraries and specify the type of the output file. To create the notch, set notch=True in the plt. Polynomial Regression is identical to multiple linear regression except that instead of independent variables like x1, x2, …, xn, you use the variables x, x^2, …, x^n. When all the people in the calss were using R, Matlab, MatPlotLib etc. Confidence intervals can also be reported in a table. 9, 20) y = 3. See installing Anaconda on Windows for installation instructions. Notched Boxplot in matplotlib. Box-Cox power transformed array. #8 Add confidence interval on barplot Barplot , Matplotlib Olivier Gaudard Consider that you have several groups, and a set of numerical values for each group. mean(rets) sigma = np. The left plot shows the noise-free objective function, the surrogate function which is the GP posterior predictive mean, the 95% confidence interval of the mean and the noisy samples obtained from the objective function so far. These still don't have attributes err_width and cap_size for end caps in type line plots with confidence intervals. set_visible(False) ax. Cite 8th Apr, 2020. CDF-based nonparametric confidence interval Metadata This file contains additional information such as Exif metadata which may have been added by the digital camera, scanner, or software program used to create or digitize it. 042) The way to interpret this confidence interval is as follows: There is a 95% chance that the confidence interval of [16. leastsq function under the hood. You don't need. A dictionary mapping each component of the boxplot to a list of the matplotlib. " When reporting confidence intervals, use the format 95% CI [LL, UL] where LL is the lower limit of the confidence interval and UL is the upper limit. Sample size for continuous data can be calculated by n is equal to 1. Bayesian optimization runs for 10 iterations. Let me know what you think. Example 1: Create a chart of the 95% confidence and prediction intervals for Example 1 of the Confidence and Prediction Intervals (whose data is duplicated in columns A and B of Figure 1). (2014, April). confidence : float If not None, plot the specified percentage confidence interval on the mean and limits of agreement. High quality Python Pandas inspired T-Shirts by independent artists and designers from around the world. Distributions module (available distributions are Exponential, Weibull, Normal, Lognormal, Gamma, Beta). bootstrapped provides pivotal (aka empirical) based confidence intervals based on bootstrap re-sampling with replacement. Line2D instances created. It is well supported in a wide range of environments such as web application servers, graphical user interface toolkits, Jupiter notebook and iPython notebook, iPython shell. test dataset 72. calibration. I recently started to use Python and I can't understand how to plot a confidence interval for a given datum (or set of data). Notched Boxplot in matplotlib. The most complex part of interpreting a statistical histogram is to get a handle on what you want to show on the x and y axes. pyplot as plt ## initialize the axes fig = plt. The process of finding standard deviation requires you to know whether the data you have is the entire dataset or it is a sample of a group. Prediction intervals provide a way to quantify and communicate the uncertainty in a prediction. norm (* args, ** kwds) = [source] ¶ A normal continuous random variable. Confidence interval answers to the question: How far is the true mean from my approximated mean? /32 Confidence intervals (2) Variance. ★ Generated confidence intervals by normality based interval, exact interval, score interval, parametric raw percentile interval and parametric bootstrap t-interval. 042) The way to interpret this confidence interval is as follows: There is a 95% chance that the confidence interval of [16. Creating a mixture model¶. Number of samples. pyplot import figure, show, rc from kapteyn import kmpfit from matplotlib. Thus, the formulas for confidence intervals for multiple linear regression also hold for polynomial regression. This helps in achieving. boxplot function. This extends the capabilities of scipy. confidence Interval: 2d array of the confidence interval for the forecast; We are forecasting the temperature for next 3 years i. If this option is not selected, the Confidence Intervals for the AUCs are calculated as AUC ± 1. Sample 1: Mean=0, SD=1, n=100, SEM=0. figure ax = fig. On top of this is plotted the 95% confidence interval for the mean (see the boxplot lectures for more information, and the yerr parameter of barcharts). load_diabetes (return_X_y = True) # Use only one feature. Matplotlib legends for mean and confidence interval plots When plotting means and confidence intervals, sometimes the mean lines are hard to see and it’s nice to have included in your legend the color of the confidence interval shading. The mathematics of testing demonstrate a confidence about how badly that assumption was broken. This data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. path import math import matplotlib. (video) In the figures below, the color. Much of that. wider for a sample size of 100 than for a sample size of 50. When polynomial fits are not satisfactory, splines may be a good alternative. Confidence intervals 50 xp Confidence interval by hand 100 xp. RandomState, optional. 042) The way to interpret this confidence interval is as follows: There is a 95% chance that the confidence interval of [16. Line2D instances created. An interval plot works best when the sample size is at least 10 for each group. More information about plotting with Matplotlib, Pandas, and Python. A common applied statistics task involves building regression models to characterize non-linear relationships between variables. std(y)/np. The percentile method is also available. Whether to plot the in-sample series. The ODS OUTPUT statement creates a data set from a table that contains the mean differences between pairs of groups, along with 95% confidence intervals for the differences. This class accepts an array or list of distribution objects created using the reliability. Matplotlib legends for mean and confidence interval plots When plotting means and confidence intervals, sometimes the mean lines are hard to see and it’s nice to have included in your legend the color of the confidence interval shading. 96 deviations, 99% will take all data within 2. This interval is such that the crystallite is small enough to not be affected by finite-size effects, but large enough to give the system time to equilibrate into a steady-state growth condition. import numpy as np import scipy. axes[1]) has the bootstrap distributions and effect sizes (with confidence intervals) plotted on it. Its value is often rounded to 1. Confidence Level – How confident you want to be. metalray Wafer-Thin Wafer. In the next example, we just add the argument reg_fit and set it to False:. The irrational number e is also known as Euler’s number. #8 Add confidence interval on barplot Barplot , Matplotlib Olivier Gaudard Consider that you have several groups, and a set of numerical values for each group. It is approximately 2. As pointed by Rothman (2016) and the American Statistical Association, relying on p-values forces a false dichotomy between results that are significant and those that are non-significant. This is the class that implements the plotting. 146810 2 1 0. The software plots the PDF and the region that corresponds to a defined confidence limit (the confidence limit used here is always equal to 95%), using the matplotlib Python module. Figure 1: Figure 1 from (Ferreira et al, 2014). ci – Confidence interval for which to compute the upper and lower bounds. There are many examples of matplotlib with PyQGIS in in GIS SE, look at How to create a x-y scatterplot from attributes in QGIS 2. medians: horizontal lines at the median of each box. Kite is a free autocomplete for Python developers. 3 Rule of Thumb For Confidence Interval Construction. use('agg') import matplotlib. boxplot(df['A'],notch= True); Plotting boxplot using seaborn. matplotlib legend and x axis interval. The former predicts continuous value outputs while the latter predicts discrete outputs. Axes, optional. Marker to use for the scatterplot glyphs. 基本の作図 例えばこんな感じのデータフレームがあったとする． x y 0 2 0. 57( q 3 – q 1 )/sqrt( n ) , where q 2 is the median (50th percentile), q 1 and q 3 are the 25th and 75th percentiles, respectively, and n is the. /32 Confidence intervals (1) We usually approximate the mean of our distribution using the samples we have. Many statistical tests will also generate a confidence interval. 50 than when the sample proportion is 0. Cite 8th Apr, 2020. How to add variable error ba. It's set up to work with the easiest case so the color_bars method has to be overridden to make it work for this case. The mathematics of testing demonstrate a confidence about how badly that assumption was broken. This helps in achieving. test dataset 72. Existing axes to plot with. Robustness of Validity: confidence intervals for the measure of variation (spread) are 95% for any distribution. How to add variable error ba. If time series is non-random then one or more of the autocorrelations will be significantly non-zero. Box-Cox power transformed array. Creating a mixture model¶. 96 multiplied by standard deviation divided by delta the whole square. Where t is the value of the Student???s t-distribution for a specific alpha. Populating the interactive namespace from numpy and matplotlib Automatic calling is: Smart = mean sd = 8000 sample_size = 25 confidence_interval = 1 * sd # The. the user can specify an accompanying median and confidence interval. Increase the confidence level, will increase the range of the interval as well. Suppose however that we want to define a 95% confidence interval, a much more natural confidence interval percentage than 95. The confidence interval is estimated using a bootstrap; for large datasets, it may be advisable to avoid that computation by setting this parameter to None. Sample-oriented task-driven visualizations: allowing users to make better, more confident decisions. The horizontal lines displayed in the plot correspond to 95% and 99% confidence bands. For more information please see: Bootstrap confidence intervals (good intro) An introduction to Bootstrap Methods; The Bootstrap, Advanced Data Analysis; When the bootstrap dosen’t work. matplotlib legend and x axis interval. barh() A simple bar chart. Preoperative variables that correlated with ER were included to generate nomogram and decision trees.


text:
# angular momentum of electron in 3rd orbital

To say an electron is in a particular orbital is meant to imply that the electron is in the quantum state which is described by that orbital. In the definition of the Keplerian Orbit Model, we presented Kepler's First and Third Laws of planetary motion. The term "orbital" was coined by Robert Mulliken in 1932 as an abbreviation for one-electron orbital wave function. Since angular momentum like linear momentum is a vector quantity, we may refer to the component of the angular momentum vector which lies along some chosen axis. When a force is applied which does change $$\vec{L}$$, a torque is said to be acting on the system. The value of l depends on the value of the principle quantum number n. The angular momentum quantum number can have positive values of zero to (n − 1). We do, however, know that the comet is famous for its short period of 76 years. Note: nh/2π gives angular momentum of electron revolving in a circular orbit as proposed by Neils Bohr. To gain a physical picture and feeling for the angular momentum it is necessary to consider a model system from the classical point of view. If the total angular momentum can be expressed approximately as the vector sum of the total orbital and spin angular momenta, the assignment is called the L-S coupling, or Russell-Saunders coupling (after the astronomer Henry Norris Russell and the physicist Frederick A. Saunders, both of the United States). can have values -3, -2, -1, 0, +1, +2, +3. The fact that angular momentum is conserved in the orbit, when coupled with an orbiting point particle of constant mass, then guarantees that this rate of change is constant. Hence, for any electron moving in kth circular orbit of radius rk, the total distance is equal to the circumference of the orbit, 2πrk. Black Friday Sale! In modern language, we might say that the derivative of this area is constant. Related questions 1) The orbital angular momentum of an electron in 2s orbital is: (IIT JEE-1996) a) 0.5h/π . 2 0 obj The physical quantity known as angular momentum plays a dominant role in the understanding of the electronic structure of atoms. Use Eq. According to Newton's second law, a force must be acting on the electron if its momentum changes with time. In summing the L and S values, only the electrons in unfilled shells (typically the outermost, or valence, shell) need be considered: in a closed subshell, there are as many electrons with spins oriented in one direction as there are with spins in the opposite direction, with the result that their orbital and spin momenta add up to zero. The letter s stood for sharp, p for principal, d for diffuse and f for fundamental in characterizing spectral lines. where M will be the mass of the sun (2.0×1030 kg). In heavier atoms, greater magnetic interactions among electrons cause L and S to be poorly defined, and these selection rules are less applicable. In this scheme, each electron n is assigned an angular momentum j composed of its orbital angular momentum l and its spin s. The total angular momentum J is then the vector addition of j1 + j2 + j3 +…, where each jn is due to a single electron. Basic features of electromagnetic radiation, Types of electromagnetic-radiation sources, Techniques for obtaining Doppler-free spectra, Total orbital angular momentum and total spin angular momentum, Coherent anti-Stokes Raman spectroscopy (CARS), Laser magnetic resonance and Stark spectroscopies. When quantum mechanics refers to the orbital angular momentum of an electron, it is generally referring to the spatial wave equation that represents the electron's motion around the nucleus of an atom. Legal. >> Which $$m_l$$ Number Corresponds to which p-Orbital? It is fixed, meaning that it is not possible to stop or accelerate the spinning. When l = 0, it is evident from Equation $$\ref{4}$$ that the angular momentum of the electron is zero. However, Hund's rule. The corresponding effect of line splitting caused by the application of a strong electric field is known as the Stark effect. The gravitational interaction between the comet and Sun produces no torque about the chosen axis. two angular-momentum eigenstates to ﬂnd a third. Electrons in free space can carry quantized orbital angular momentum (OAM) projected along the direction of propagation. For n = 4, the possible 'l' values are 0, 1, 2 & 3. The preceding discussion referred to the 1s orbital since for the ground state of the hydrogen atom $$n = 1$$ and $$l = 0$$. \begin{align} |\psi_{2,1,0} \rangle &=r \cos θR(r) \\[4pt] |\psi_{2,1,+1} \rangle &=−\dfrac{r}{2} \sinθ e^{iϕ} R(r) \\[4pt] |\psi_{2,1,-1} \rangle &=+\dfrac{r}{2} \sinθ e^{-iϕ} R(r) \end{align}. Third, the e g metal d ... "Orbital angular momentum is generated when an electron in an orbital of a degenerate set of orbitals is moved to another orbital in the set by rotation. The angular momentum (mvr) of electron in nth orbit is equal to nh/2π.

Expository Paragraph Examples For Elementary, Hanging Pitcher Plant Seeds, Hearty One Dish Vegetarian Meals, Evaluation Criteria In Project Management, Swimming Pool Clipart Black And White, Kobalt 0300841 Parts, No Mow Grass For Slopes, Test Lead Connectors, Boys Latin Panda Bear, Kumho Kh27 Review, Adaptations Of An Elephant To Keep Cool, Rules For Charades On Zoom, Lamy Turquoise Ink Cartridges, Braun 4199 Parts, Narrative Writing Topics, Bike Ride Quotes, Private High Schools In Chicago, Youtube Feuds Of 2019, Global Health Essay Topics, Stem Definition Lgbt, Proud Of You Quotes For Friend, Motivational Influencer Definition, Australorp Vs Rhode Island Red, Anderson Lake Algae, Pool Essentials Shock Walmart, Coleus Canina Plant, Used Cars For Sale Private Owner Sacramento, Ca, Awards Of Rabindranath Tagore, Lake Chelan Camping, How To Fix Hosta Scorch, Is It Illegal To Swim In A River, Bakkies For Sale Under R50000, Salt Water Benefits For Skin, What Is Data Analysis Software,

format: plain


text:
## Monday, April 30, 2018

### The Birthday Problem

The Birthday problem is one of the classic problems in Probability theory concerning the probability that, in a set of $n$ randomly chosen people, some pair will have a the same birthday. The idea in this post is to generalize this setup and find the expected value in this generalization.

The generalization here is this: Assume that there is a very long line of persons ready to enter a very large room one by one. Each person is let in and declares her birthday upon entering the room. How many people, on average, must enter in order to find $k$ people that have birthdays that are $d$ days apart (given an $r$-day year)?

Non-Spoiler: Some readers may recognize that this Problem 584 of Project Euler. But note that this post neither gives the answer nor the right way to solve that problem. All we are going here is find an approximation of the required value which is far off from the correct answer.

Well, when we say 'approximation', we are immediately reminded of the Poisson approximation of the Birthday problem in Wikipedia. But the idea here is that most of the approximations I found in the web concerns only about the probability and not about the expected value.  A special case of this problem is solved in Strategic Practice 5 of the (amazing) Stat 110 course by the (extraordinary) Prof. Joseph Blitzstein. And I got curious as to how good the approximation really is.

Let $\mathbb{E}(k,d,r)$ be the expected number of people that have to enter room such that we have $k$ people with birthdays $d$ days apart for the first time.

Let $X_n$ be the number of $k$-set birthday matches in when $n$ people have entered the room. By the Poisson paradigm, $X_n$ can be considered to be a poisson variable. The parameter $\lambda_n$ for this variable is given by,

$\displaystyle\lambda_n=\displaystyle\binom{n}{k}\cdot\frac{1}{(k-1)!}\left(\frac{2d+1}{r}\right)^{k-1}$  (why?)

Therefore we immediately have, $\mathbb{P}(X_n=0)=e^{-\lambda_n}$

Now by a simple trick common in evaluating expected values, we have,

\begin{align} \displaystyle\mathbb{E}(k,d,r)&=k+\sum_{n=k}^\infty\mathbb{P}(X_n=0)=k+\displaystyle\sum_{n=k}^\infty e^{-\lambda_n} \end{align}

Though we have an infinite sum, the numbers decrease rapidly because of the exponential factor. For the values given the said Project euler problem, this approximation gives $\mathbb{E}_{\text{Poisson}}(3,1,10)\approx 6.15092$ and $\mathbb{E}_{\text{Poisson}}(3,7,100)\approx 8.79751$

But we can take it a little further. When the parameter of a Poisson variable get very large, then the Normal variable with the same mean and variance as the Poisson variable gives better accuracy. Therefore,

\begin{align} \displaystyle\mathbb{E}(k,d,r)&=k+\sum_{n=k}^\infty\mathbb{P}(X_n=0)\\ &=k+\displaystyle\sum_{n=k}^\infty \mathbb{P}(-1/2 \leq X_n \leq 1/2) \end{align}

where $X_n \sim \mathcal{N}(\lambda_n,\lambda_n)$ along with the continuity correction.

Here again, the numbers decrease fast and the sum converges in about fifty terms. Now we have $\mathbb{E}_{\text{Normal}}(3,1,10)\approx 5.68554$ and $\mathbb{E}_{\text{Normal}}(3,7,100)\approx 8.04791$

In fact for the required answer, the normal approximation gives $\mathbb{E}_{\text{Normal}}(4,7,365)\approx 33.6396$ with a relative error of just about $2.5\%$. Not bad.

These values were calculated with the following Mathematica code.

Clear["Global*"];
PoissonApprox[k_, d_, r_] :=
k + Sum[N[
Exp[-Binomial[n, k] Power[(1 + 2 d)/r, k - 1]/
Factorial[k - 1]]], {n, k, 100}];
NormalApprox[k_, d_, r_] :=
k + Sum[N[
CDF[NormalDistribution[
Binomial[n, k] Power[(1 + 2 d)/r, k - 1]/Factorial[k - 1],
Sqrt[Binomial[n, k] Power[(1 + 2 d)/r, k - 1]/
Factorial[k - 1]]], 1/2] -
CDF[NormalDistribution[
Binomial[n, k] Power[(1 + 2 d)/r, k - 1]/Factorial[k - 1],
Sqrt[Binomial[n, k] Power[(1 + 2 d)/r, k - 1]/
Factorial[k - 1]]], -1/2]], {n, k, 100}]
PoissonApprox[4, 7, 365]
NormalApprox[4, 7, 365]

Hope you enjoyed this. See you again with a nice problem.

Until then
Yours Aye
Me

## Tuesday, April 24, 2018

### Probability on a Chess Match

Consider two friends $A$ and $B$ playing a series of bullet chess games. As every time the player who lost the recent game wants to continue, they come with an idea. They'll play the first game. After the game, they'll toss a fair coin. If the coin comes up heads, they'll continue playing another game, else they end the match. They'll continue this procedure until the coin turns up Tails.

The question we are interested here is the probability of either player winning the match given the probability $\alpha$ of $A$ winning a game, probability $\gamma$ of $B$ winning a game and the remaining probability $\beta=1-\alpha-\gamma$ of a game ending in a draw. WLOG assume $\alpha<\gamma$.

All the equations referred in this post now on are from A list of Integrals and Identities.

Let $A_{n,k}$ denote the event of $A$ winning a match of $n$ games by $k$ more wins (ignoring the coin tosses). Then,

$\displaystyle\mathbb{P}(A_{n,k})=\sum_{a+b+c =n\\a-c=k}\binom{n}{a,b,c}\alpha^a\beta^b\gamma^c$

where $a$ denotes the number of games won by $A$, $c$ the number of games won by $B$ and $b$ the number of games that ended in a draw.

First, let's tackle an easy question. That is finding the probability of the match ending in a draw.

\begin{align} \mathbb{P}(\text{Draw})&=\displaystyle\sum_{n=1}^\infty\mathbb{P}(A_{n,0}\text{ | }n\text{ games played})\cdot\mathbb{P}(n\text{ games being played})\\ \end{align}

As we know that the probability of the match lasting $n$ games is $2^{-n}$, using (1) we have,

\begin{align} \mathbb{P}(\text{Draw})&=\displaystyle\frac{\cot\phi}{\sqrt{\alpha\gamma}}-1\\ \end{align},   where $\phi=\cos^{-1}\displaystyle\left(\frac{2\sqrt{\alpha\gamma}}{1+\alpha+\gamma}\right)$

Similarly, we now look at the probability of $A$ not losing the match. This time we have,

\begin{align} \mathbb{P}(A \text{ not losing})&=\displaystyle\sum_{n=1}^\infty\sum_{k=0}^\infty\mathbb{P}(A_{n,k}\text{ | }n\text{ games played})\cdot\mathbb{P}(n\text{ games being played})\\ \end{align}

Using (6), this reduces to,

\begin{align} \mathbb{P}(A \text{ not losing})&=\displaystyle\frac{\cot\phi}{\sqrt{\alpha\gamma}-\alpha(\sec\phi-\tan\phi)}-1\\ \end{align}

In fact, instead of using a fair coin, if they decide to use a biased coin so that they continue playing with probability $q$ and end the match with probability $p=1-q$,

\begin{align} \displaystyle\frac{q}{1-q}\mathbb{P}(\text{Draw})&=\frac{\frac{1}{2}\cot\phi}{\sqrt{(q\alpha)(q\gamma)}}-1\\ \end{align}

$\displaystyle\frac{q}{1-q}\mathbb{P}(A \text{ wins the match})=\displaystyle\frac{\frac{1}{2}\cot\phi}{(q\gamma)(\sec\phi+\tan\phi)-\sqrt{(q\alpha)(q\gamma)}}$

$\displaystyle\frac{q}{1-q}\mathbb{P}(B \text{ wins the match})=\displaystyle\frac{\frac{1}{2}\cot\phi}{(q\alpha)(\sec\phi+\tan\phi)-\sqrt{(q\alpha)(q\gamma)}}$

where $\displaystyle\phi=\cos^{-1}\left(\frac{2\sqrt{(q\alpha)(q\gamma)}}{(1-q)+q\alpha+q\gamma}\right)$

These expressions can be written algebraically without the use of trigonometric functions but they are clumsy and I prefer this form. Also, there a couple of nice details hidden in these expressions. First, using a right choice of $q$, the weaker player will be able to decrease his opponent's chance of winning the match which was surprising for me.

Second, in the interesting and limiting case of $q\to1$, the LHSs of the above three expression can be seen as the expected number of games after which the match is at a drawn stage, player $A$ is in the lead and player $B$ is in the lead respectively.

$\displaystyle\lim_{q\to1}\displaystyle\frac{q}{1-q}\mathbb{P}(\text{Draw})=\frac{1}{|\gamma-\alpha|}-1$,

$\displaystyle\lim_{q\to1}\displaystyle\frac{q}{1-q}\mathbb{P}(A \text{ wins the match})=\frac{\alpha}{\text{max}(0,\gamma-\alpha)^2}$ and

$\displaystyle\lim_{q\to1}\displaystyle\frac{q}{1-q}\mathbb{P}(B \text{ wins the match})=\frac{\gamma}{\text{max}(0,\alpha-\gamma)^2}$

ASIDE: An interesting discussion on a related problem is given in Joint probability of geometric random variables. However, there the distributions are independent. Our problem can be stated similarly using the result that if,

$\vec{\mathbf{X}}\sim \text{Mult}(N, \vec{\mathbf{p}})$ where $N \sim \text{NBin}(m,s)$, then $X_i \sim \displaystyle\text{NBin}\left(m,\frac{s}{s+(1-s)p_i}\right)$

But the $X_i$'s are not independent (they would be had $N$ been a Poisson variable).

Even though we started with the assumption $\alpha<\gamma$, fortunately the final results holds for all values of $\alpha$ and $\gamma$. The symmetry of the formulae is really enchanting to me and greatly satisfied that I've solved this. Hope you enjoyed it.

Until then
Yours Aye
Me

### A List of Integrals and Identities

A list the integrals and identities used in solving the problem in this post.

Throughout this post we consider $0<\alpha, \gamma,r \leq 1$ and $a, b, c, k$ is a non-negative integer.

(1) I'm not sure where I saw this. I'll update the reference if I find it. UPDATE: I found the reference. It's given in Advances in Combinatorial Methods and Applications to Probability and Statistics

$\displaystyle\sum_{a,b,c \geq 0 \\ a+b+c=n \\ a-c=k}\binom{n}{a,b,c}\alpha^a(1-\alpha-\gamma)^b\gamma^c=\frac{(\alpha/\gamma)^{k/2}}{\pi}\int_0^\pi \cos k\theta\text{ } (1-\alpha-\gamma+2\sqrt{\alpha\gamma}\cos \theta)^n \, d\theta$

(2) This is given in Generality of algebra. Anyway, this is easy to prove if we recognize $r^k \cos kx=\text{Re}(r^k e^{ikx})$ and it's just a geometric series.

$1+r\cos x+r^2 \cos 2x+r^3 \cos 3x+\cdots=\displaystyle\frac{1-r\cos x}{1-2r\cos x+r^2}$

(3) This is just pattern recognition by using different values in Mathematica.

$\displaystyle\int \frac{1-r \cos x}{1-2r \cos x +r^2}\,dx=\frac{x}{2}+\tan^{-1}\left(\frac{1+r}{1-r}\tan\left(\frac{x}{2}\right)\right)+\text{constant}$

Interestingly,

$\displaystyle\frac{1}{\pi}\int_0^\pi \frac{1-r \cos x}{1-2r \cos x +r^2}\,dx=H[1-r]$

where $H[x]$ is the Heaviside Unit step function.

(4) I definitely saw this Wikipedia. But again I couldn't find it now. UPDATE: Found this too in List of definite integrals.

$\displaystyle\frac{1}{\pi}\int_0^\pi\frac{\cos kx}{\sec \phi-\cos x}\,dx=\frac{(\sec \phi - \tan \phi)^k}{\tan \phi}$

(5) Using $k=0$ in (4),

$\displaystyle\frac{1}{\pi}\int_0^\pi\frac{1}{\sec \phi-\cos x}\,dx=\cot\phi$

(6) Multiplying (4) by $r^k$ and summing across all $k$,

$\displaystyle\frac{1}{\pi}\int_0^\pi\frac{1+r\cos x+r^2 \cos 2x+r^3 \cos 3x+\cdots}{\sec \phi-\cos x}\,dx=\frac{\cot \phi}{1-r(\sec \phi - \tan \phi)}$

Until then
Yours Aye
Me

## Thursday, April 19, 2018

### A mild generalization of the Ménage problem

We all know about the classic Ménage problem which for the number of different ways in which it is possible to seat a set of male-female couples at a dining table so that men and women alternate and nobody sits next to his or her partner.

Here again we consider a similar setup except each family consists four members, a father, mother, a son and a daughter. To be clear, we seek the number of different ways in which it possible to seat a set of families at a dining table so that men and women alternate and no family end up sitting together. Note that we consider a family to be sitting together only when all members of the same family sit next to each other.

The idea here is inspired by the Non-sexist solution of the menage problem. It is easy to see that there are $2(2n)!^2$ seatings in total such that the dinner table has a male-female arrangement. That is, $2$ ways to decide which seat is for men/women; $(2n)!$ ways each for men and women.

Consider $n>1$. Let $L_n$ be the answer we are trying to find for the case of $n$ families. Then, using inclusion-exclusion, we have

$L_n=\displaystyle\sum_{k=0}^n(-1)^k\binom{n}{k}w_k$

where $w_k$ denotes the number of seatings such that a given set of $k$ families are seated together (There maybe other families sitting together as well but we don't care about them). To compute $w_k$, let's define $d_k$ which is the number of ways of covering a circle containing $4n$ equally spaced points with a curved domino that spans $4$ points.

Calculation of $d_k$'s are very easy. It is just the stars and bars problem on a circular setup. For the problem at hand, we have,

$d_k=\displaystyle\frac{4n}{4n-3k}\binom{4n-3k}{k}$

The idea for the above formulae is exactly like that of this Stack Exchange question.

Now, we compute $w_k$. Note that there are $8$ ways in which a family can be seated together with men and women alternating

If we are done choosing $k$ families, we have $2$ ways to decide on which are men's seats and which are women's. We have $d_k$ ways to seat these $k$ families in the circular table. The families can be permuted in $k!$ ways. As we have selected men's (and women's) seats, each of the $k$ families that are supposed to sit together, can have $4$ ways of being seated. The remaining $2n-2k$ men and $2n-2k$ women can be permuted in the remaining seats. In short, we have,

$w_k=2\cdot d_k \cdot 4 ^k \cdot k! \cdot (2n-2k)!^2$

Therefore,

$L_n=\displaystyle\sum_{k=0}^n(-1)^k\binom{n}{k}\cdot 2\cdot 4^k\cdot k!\cdot (2n-2k)!^2\cdot d_k$

Substituting $d_k$, and simplifying we finally end up with,

$L_n=2\cdot n!\displaystyle\sum_{k=0}^n(-4)^k\frac{4n}{4n-3k}\binom{4n-3k}{k}\frac{(2n-2k)!^2}{(n-k)!}$

And there we have our final answer.

Another interesting variation in our 'generalized menage problem' is asking for the number of ways such that no two members of the same family sit together. This seems rather complicated in that it doesn't seem to admit any closed form. Of course, this is just my opinion.

Trying to find an answer to this variation, I started thinking about arranging balls of $n$ different colors with $c[i]$ balls of color $i$. Seems DP is the best approach as discussed in AMBALLS - Editorial. But let's postpone that for a later post.

Hope you enjoyed this post. I'll write again with a nice post.

Until then
Yours Aye
Me

## Monday, February 19, 2018

### Python Code - Gauss's Circle Problem

This code uses the algorithm discussed here.

Iterative version of the code - Python

from math import sqrt, ceil, floor
from timeit import default_timer

start = default_timer()

def matmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])

if cols_A != rows_B:
print("Cannot multiply the two matrices. Incorrect dimensions.")
return

# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]

for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
return C

def gauss(n):
sn = ceil(sqrt(n))
res = 0
stk = [([[1, 0, 0], [0, 1, 0], [0, 0, -n]], sn, sn)]
while stk:
m, w, h = stk.pop()
if w <= 0 or h <= 0:
continue
a, b, c, d, e, f = m[0][0], 2 * m[0][1], m[1][1], 2 * m[0][2], 2 * m[1][2], m[2][2]
if d * d - 4 * a * f < 0 or e * e - 4 * c * f < 0:
res += w * h
continue
x0, y0 = (- d + sqrt(d * d - 4 * a * f)) / 2 / a, (- e + sqrt(e * e - 4 * c * f)) / 2 / c
xint, yint, uint, vint, flag = 0, 0, 0, 0, 0
if floor(x0) == ceil(x0):
xint = 1
if floor(y0) == ceil(y0):
yint = 1
if w <= 1:
res += (h - ceil(y0)) * w - yint
continue
if h <= 1:
res += (w - ceil(x0)) * h - xint
continue
if w - x0 > 1:
res += (w - ceil(x0)) * h - xint
stk.append((m, ceil(x0), h))
continue
if h - y0 > 1:
res += (h - ceil(y0)) * w - yint
stk.append((m, w, ceil(y0)))
continue
temp = (a - b + c) * (c * d * d - b * d * e + a * e * e + b * b * f - 4 * a * c * f)
if temp < 0:
continue
u = ((a - b + c) * (b * e - 2 * c * d) - (b - 2 * c) * sqrt(temp)) / (a - b + c) / (4 * a * c - b * b)
if floor(u) == ceil(u):
uint = 1
if u > w:
u, flag = w, 1
if u < 0:
u, flag = 0, 1
temp = (e  + b * u) * (e + b * u) - 4 * c * (f + u * (d + a * u))
if temp < 0:
continue
v = (- e - b * u + sqrt(temp)) / 2 / c
if floor(v) == ceil(v):
vint = 1
if v < 0:
v = 0
u, v = ceil(u), ceil(v)
if u == w and v == h:
continue
if uint == 1 and vint == 1 and flag == 0:
res -= 1
res += (w - u + h - 1 - v) * (w - u + h - v) // 2
stk.append((matmult(matmult([[1, 0, 0], [-1, 1, 0], [h - v, v, 1]], m), [[1, -1, h - v], [0, 1, v], [0, 0, 1]]), u - (h - v), h - v))
stk.append((matmult(matmult([[1, -1, 0], [0, 1, 0], [u, w - u, 1]], m), [[1, 0, u], [-1, 1, w - u], [0, 0, 1]]), w - u, v - (w - u)))
res = (sn - 1) * (sn - 1) - res
res += sn - 1
res *= 4
res += 1
if sn * sn == n:
res += 4
return res

print(gauss(10 ** 20))
print(default_timer() - start)

Recursive version of the code - Python

from math import sqrt, ceil, floor
from timeit import default_timer

start = default_timer()

def matmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])

if cols_A != rows_B:
print("Cannot multiply the two matrices. Incorrect dimensions.")
return

# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]

for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
return C

def poins(m, w, h):
res = 0
if w <= 0 or h <= 0:
return 0
a, b, c, d, e, f = m[0][0], 2 * m[0][1], m[1][1], 2 * m[0][2], 2 * m[1][2], m[2][2]
if d * d - 4 * a * f < 0 or e * e - 4 * c * f < 0:
return w * h
x0, y0 = (- d + sqrt(d * d - 4 * a * f)) / 2 / a, (- e + sqrt(e * e - 4 * c * f)) / 2 / c
xint, yint, uint, vint, flag = 0, 0, 0, 0, 0
if floor(x0) == ceil(x0):
xint = 1
if floor(y0) == ceil(y0):
yint = 1
if w <= 1:
return (h - ceil(y0)) * w - yint
if h <= 1:
return (w - ceil(x0)) * h - xint
if w - x0 > 1:
return (w - ceil(x0)) * h - xint + poins(m, ceil(x0), h)
if h - y0 > 1:
return (h - ceil(y0)) * w - yint + poins(m, w, ceil(y0))
temp = (a - b + c) * (c * d * d - b * d * e + a * e * e + b * b * f - 4 * a * c * f)
if temp < 0:
return 0
u = ((a - b + c) * (b * e - 2 * c * d) - (b - 2 * c) * sqrt(temp)) / (a - b + c) / (4 * a * c - b * b)
if floor(u) == ceil(u):
uint = 1
if u > w:
u, flag = w, 1
if u < 0:
u, flag = 0, 1
temp = (e  + b * u) * (e + b * u) - 4 * c * (f + u * (d + a * u))
if temp < 0:
return 0
v = (- e - b * u + sqrt(temp)) / 2 / c
if floor(v) == ceil(v):
vint = 1
if v < 0:
v = 0
if uint == 1 and vint == 1 and flag == 0:
res -= 1
u, v = ceil(u), ceil(v)
if u == w and v == h:
return 0
res += (w - u + h - 1 - v) * (w - u + h - v) // 2
res += poins(matmult(matmult([[1, 0, 0], [-1, 1, 0], [h - v, v, 1]], m), [[1, -1, h - v], [0, 1, v], [0, 0, 1]]), u - (h - v), h - v)
res += poins(matmult(matmult([[1, -1, 0], [0, 1, 0], [u, w - u, 1]], m), [[1, 0, u], [-1, 1, w - u], [0, 0, 1]]), w - u, v - (w - u))
#print(m, w, h, u, v, res)
return res

def gauss(n):
m = ceil(sqrt(n))
res = poins([[1, 0, 0], [0, 1, 0], [0, 0, -n]], m, m)
res = (m - 1) * (m - 1) - res
res += m - 1
res *= 4
res += 1
if m * m == n:
res += 4
return res

print(gauss(10 ** 14))

print(default_timer() - start)

Recursive version of the code

Clear["Global*"];
Poins[m0_, w0_, h0_] :=
Poins[m0, w0, h0] =
Block[{$RecursionLimit = Infinity, m = m0, w = w0, h = h0, a, b, c, d, e, f, temp, u, v, res = 0, trans, x0, y0, Flag = 0}, If[Or[w <= 0, h <= 0], Return[0];]; If[w < h, temp = {{0, 1, 0}, {1, 0, 0}, {0, 0, 1}}; m = Transpose[temp].m.temp; temp = w; w = h; h = temp; ]; a = m[[1, 1]]; b = 2 m[[1, 2]]; c = m[[2, 2]]; d = 2 m[[1, 3]]; e = 2 m[[2, 3]]; f = m[[3, 3]]; If[Or[d*d - 4*a*f < 0, e*e - 4*c*f < 0], Return[w h];]; x0 = (-d + Sqrt[d*d - 4*a*f])/2/a; y0 = (-e + Sqrt[e*e - 4*c*f])/2/c; If[w <= 1, Return[(h - Ceiling[y0]) w - Boole[IntegerQ[y0]]];]; If[h <= 1, Return[(w - Ceiling[x0]) h - Boole[IntegerQ[x0]]];]; If[w - x0 > 1, Return[(w - Ceiling[x0]) h - Boole[IntegerQ[x0]] + Poins[m, Ceiling[x0], h]]; ]; If[h - y0 > 1, Return[(h - Ceiling[y0]) w - Boole[IntegerQ[y0]] + Poins[m, w, Ceiling[y0]]]; ]; temp = (a - b + c)*(c*d*d - b*d*e + a*e*e + b*b*f - 4*a*c*f); If[temp < 0, Return[0];]; u = ((a - b + c)*(b*e - 2*c*d) - (b - 2*c)*Sqrt[temp])/(a - b + c)/(4*a*c - b*b); If[u > w, u = w; Flag = 1;]; If[u < 0, u = 0; Flag = 1;]; temp = (e + b*u)*(e + b*u) - 4*c*(f + u*(d + a*u)); If[temp < 0, Return[0];]; v = (-e - b*u + Sqrt[temp])/2/c; If[v < 0, v = 0;, v = Ceiling[v];]; If[And[IntegerQ[u], IntegerQ[v], Flag == 0], res -= 1;]; u = Ceiling[u]; v = Ceiling[v]; If[And[u == w, v == h], Return[0];]; res += (w - u + h - 1 - v)*(w - u + h - v)/2; trans = {{1, -1, h - v}, {0, 1, v}, {0, 0, 1}}; res += Poins[Transpose[trans].m.trans, u - (h - v), h - v]; trans = {{1, 0, u}, {-1, 1, w - u}, {0, 0, 1}}; res += Poins[Transpose[trans].m.trans, w - u, v - (w - u)]; res ]; GaussCnt[n0_] := Block[{n = n0, m, res}, m = Ceiling[Sqrt[n]]; res = Poins[{{1, 0, 0}, {0, 1, 0}, {0, 0, -n}}, m, m]; res = (m - 1)*(m - 1) - res; res += m - 1; res *= 4; res += 1; If[m m == n, res += 4;]; res ]; Rad = Power[10, 6]; GaussCnt[Rad*Rad] // AbsoluteTiming Note that in all the codes, the core function takes as input the square of the radius of the circle under consideration. Until then Yours Aye Me ### A Sub-linear algorithm for Gauss's Circle problem I was proud of my previous two posts, I thought I would not have anything that I can share for a while. But I'm glad I found something very interesting. I found this PDF titled A Successive approximation Algorithm for Computing the Divisor Summatory function a long time back (in OEIS I think). It has an$O(n^{1/3})$for calculating the divisor summatory function. I have read this many times both because I find it interesting and I could not fully understand the tiny details though I got the crux of what the algo is trying to do. I was reading it again some time last week and was on page 6. The PDF uses the properties of a Hyperbola to do the summation and the author quotes "... the hyperbolic segment has the same basic shape as the full hyperbola" and then suddenly it hit me. After all, the Hyperbola is a conic section and if it holds for a hyperbola, why not a different conic? And if that conic is an Ellipse (of which Circle is a special case), then pretty much the same algo should solve Gauss's Circle problem. Indeed it did. As I said earlier, I could not get all the details of the original algo and I proceeded in a more natural way. In essence, let$C(x,y)=Ax^2+Bxy+Cy^2+Dx+Ey+F=0$be a conic section with an increasing slope in the first quadrant bounded by the lines$x=w$and$y=h$. Then we will the counting the lattice points such that,$0 \leq x < w$,$0 \leq y < h$and$C(x,y) > 0$Consider the first quadrant of the circle as shown in the left figure below. Now we can draw an 'almost' tangent with a slope of$-1$as shown in the right figure below. Let$(u,v)$be the almost tangent point (shown as a black dot). Now it's we can simply count the number of lying inside the triangle that don't violate our conditions in$O(1)$time. We can then make two parallelograms such that they cover our region of interest. Something like in the figure below. Now comes the beautiful part. Let's concentrate on the parallelogram above. The reasoning will be almost similar to the other parallelogram except for a tiny detail. We can transform the co-ordinate system now such that the lower left corner of the upper parallelogram becomes the origin. In addition to this, the parallelogram can be sheared horizontally such that the parallelogram becomes a rectangle. Simply put, we are trying to do the following: Here the first figure, which is the upper parallelogram, after shifting the origin and shearing becomes the second figure. Note that the number of lattice points inside both the figures remain the same after this operation. This fact can be understood by a bit of linear algebra but let's not get into the details. Now we are in the same situation as before. We have a conic, a bounding rectangle and we have to count the points inside the rectangle and outside the conic. This essentially forms the crux of the recursion. The almost tangent point can be found as the point of intersection of the conic and the tangent (with a slope of$-1$) equation of the same conic. Mathematica solves the symbolic equation in the blink of an eye. The 'exact' point of intersection$(u, v)$is found to be,$u_e=\displaystyle\frac{(A-B+C)(BE-2CD)-(B-2C)\sqrt{\Delta_u}}{(A-B+C)(4AC-B^2)}$and$v_e=\displaystyle\frac{-C-Bu+\sqrt\Delta_v}{2C}$where$\Delta_u=(A - B + C) (CD^2 - BDE + AE^2 + B^2F - 4ACF)$and$\Delta_v=(E+Bu)^2 - 4C(F + u (D + Au))$The almost tangent point can be found by setting$u=\lceil u_e \rceil$and$v=\lceil v_e \rceil$. Now the transformation. These can be attained beautifully with matrices. A Conic can be represented as a matrix in the following way.$C=\mathbf{x}^T A_Q\mathbf{x}$where the matrix$A_Q$is given in Matrix representation of Conic Sections. Now the 'shifting and shearing' operations can be done using the following two matrices.$X=\begin{pmatrix}1 & -1 & h-v\\0 & 1 & v \\0&0&1\end{pmatrix}$and$Y=\begin{pmatrix}1 & 0 & u\\-1 & 1 & w-u \\0&0&1\end{pmatrix}$Now the matrix$X^TA_QX$gives the conic after we have translated the origin to$(u, v)$and sheared it horizontally and vice versa for the vertical shearing using matrix$Y$. Finally, though we start with a simple conic, the conics that subsequently results in further recursion are a little tricky and there are a number of cases that have to dealt with carefully. A better programmer could've done it in a day or two, but it took me almost ten days to finally complete the code. You can find the recursive and the iterative version of the Python code in this post. Assuming no precision issues, the iterative version of the code finds$N(10^{9})=3141592653590319313$in about 5 mins and$N(10^{10})=314159265359046103545$in about 20 mins. The timing could be halved by taking the eight-fold symmetry of a circle but I didn't do it yet. Hope you enjoyed it. See ya in the next post. Until then Yours Aye Me ## Sunday, January 21, 2018 ### Complicating a simple Probability Problem II Hi all, we complicated a simple problem in Probability in the previous post. Here again, we do the same thing. The setup is this. Consider the unit interval$(0, 1)$. We start at the origin and choose$n$random points in the interval that lies to the right. We now choose the$k$th point nearest to the origin and move there. We again choose$n$points in the interval that lies to the right and keep moving to the right until we get inside an interval$[0, x)$for a given$x$. Let$\mathbb{E}_{n,k}(x)$be the expected number of times we have to generate the numbers (or in other words, the moves we have to make). So as you may have guessed, this post about finding this number. Okay, the procedure pretty much follows what we saw the previous time. It gets all messy and I'm not even sure how to present it. So I'm directly giving the result. Let$P_{n,k}(z)$denote the characteristic equation. We have,$P_{n,k}(z)=\displaystyle\frac{z^\underline{n}}{n!}-(-1)^{n-k}\sum_{j=0}^{n-k}(-1)^j\binom{n-1-j}{k-1}\frac{z^\underline{j}}{j!}$where$z^\underline{n}$is the falling factorial. Let$\eta_1,\eta_2,\cdots,\eta_n$be the$n$roots of the equation$P_{n,k}(z)=0$. Then we have,$\begin{align}
\mathbb{E}_{n,k}(x)=\displaystyle\frac{H_n-\log{x}}{H_n-H_{n-k}}&+\frac{x^n}{n!}\sum_{r=1}^n\frac{x^{-\eta_r}\eta_r^\underline{n}}{\eta_rP'_{n,k}(z)}\\
&-\displaystyle\frac{x^nn^{n-1}}{n!(H_n-H_{n-k})}\sum_{r=1}^n\sum_{i=0}^{n-1}\sum_{j=0}^i\frac{(n-i)x^{-\eta_r}\eta_r^\underline{n}\eta_r^{j-1}a_{i-j}}{n^{i}P'_{n,k}(\eta_r)}
\end{align}$where$a_m=[z^{n-m}]P_{n,k}(z)$and$H_n$is the$n$th Harmonic number. Using this, we can see that$\mathbb{E}_{n,1}(x)=1-n\log{x}\mathbb{E}_{n,2}(x)=1+\displaystyle\frac{n(n-1)}{(2n-1)^2}(x^{2n-1}-1)-\frac{n(n-1)\log{x}}{2n-1}\$

Considering the number of identities involving the falling factorials, there seems to enough room for simplifying the above formula but am not able to see things clearly. I think adding an animation would make it more easy to see what the 'procedure' means and am on it. I'll update it as soon as possible.

Until then
Yours Aye
Me


text:
Basic College Mathematics (10th Edition)

Convert the fraction in the percent into a decimal and divide the percent by 100. Fill in the percent equation. part=(percent)(whole) $370=(0.185)x$ Divide both sides by the percent: $2000=x$


text:
# Critical exponents in Monte Carlo simulations

1. Aug 2, 2013

### LagrangeEuler

In Monte Carlo simulation of classical spin systems I have a trouble to determine critical exponent $\alpha$.
$M \propto L^{-\frac{\beta}{\nu}}$
$\chi \propto L^{\frac{\gamma}{\nu}}$
$C_V \propto L^{\frac{\alpha}{\nu}}$
Is this correct? From that slope of the curve $\ln Cv$ as a function of $\ln L$ determines $\frac{\alpha}{\nu}$. There is relation $2-\alpha=d\nu$, where $d$ is dimension of the lattice. What is a problem with determining $\alpha$? I didn't get exponent $\alpha$ from the table for $2d$ and $3d$ Ising model.

Last edited: Aug 2, 2013
2. Aug 17, 2013

### LagrangeEuler

Maybe there is some different way for calculating critical exponents in simulation. If you know that another way please tell me. Tnx.


text:
Reconstructing the EUV Spectrum of Star-forming Regions from Millimeter Recombination Lines of H I, He I, and He II

Murchikova, Lena; Murphy, Eric J.; Lis, Dariusz C.; Armus, Lee; de Mink, Selma; Sheth, Kartik; Zakamska, Nadia; Tramper, Frank; Bongiorno, Angela; Elvis, Martin; Kewley, Lisa; Sana, Hugues

The Astrophysical Journal, 903 29 (2020)

Abstract

The extreme ultraviolet (EUV) spectra of distant star-forming regions cannot be probed directly using either ground- or space-based telescopes due to the high cross section for interaction of EUV photons with the interstellar medium. This makes EUV spectra poorly constrained. The millimeter/submillimeter recombination lines of H and He, which can be observed from the ground, can serve as a reliable probe of the EUV. Here we present a study based on ALMA observations of three Galactic ultracompact H II regions and the starburst region Sgr B2(M), in which we reconstruct the key parameters of the EUV spectra using millimeter recombination lines of H I, He I, and He II. We find that in all cases the EUV spectra between 13.6 and 54.4 eV have similar frequency dependence: ${L}_{\nu }\propto {\nu }^{-4.5\pm 0.4}.$ We compare the inferred values of the EUV spectral slopes with the values expected for a purely single stellar evolution model (Starburst99) and the Binary Population and Spectral Synthesis code (BPASS). We find that the observed spectral slope differs from the model predictions. This may imply that the fraction of interacting binaries in H II regions is substantially lower than assumed in BPASS. The technique demonstrated here allows one to deduce the EUV spectra of star-forming regions, providing critical insight into photon production rates at $\lambda \leqslant 912\mathring{{\rm{A}}}$ , and can serve as calibration to starburst synthesis models, improving our understanding of star formation in the distant universe and the properties of ionizing flux during reionization.

Keywords: Astrophysicists;Interstellar medium;Star-forming regions;Star formation;Radiative recombination;Compact H II region;105;847;1565;1569;2057;286;Astrophysics – Astrophysics of Galaxies;Astrophysics – Solar and Stellar Astrophysics


text:
GLSL Fragment Shader compiles fine on certain computers [closed]

I got this piece of code in a fragment shader:

if (color.a < 0.01f)

It runs fine on an older graphic card but can't even compile on my newer (maybe not new, but..) GTX 770. I got the most recent drivers and everything. The versions is correct. OpenGL 4.4. The shader compiles like normal if I remove the discard statement.

closed as off-topic by Nicol Bolas, Maximus Minimus, Trevor Powell, Gnemlock, DMGregory♦May 21 '17 at 13:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Questions about debugging a problem must provide a minimal, complete, verifiable example of the issue so that readers can diagnose it without needing to guess, read all of your code, or engage in extensive back-and-forth dialog. For more information, see this meta thread." – Nicol Bolas, Trevor Powell, Gnemlock, DMGregory
If this question can be reworded to fit the rules in the help center, please edit the question.

• Can you obtain any information about the specific compilation error that's occurring? – DMGregory May 20 '17 at 17:50
• Possible duplicate of glsl Expected token ')', found 'identifier' with function mix – Maximus Minimus May 20 '17 at 20:51
• This might be better suited for Computer Graphics StackExchange – Archmede May 21 '17 at 1:02
• Really needs the whole shader and the glGetShaderInfoLog() messages to diagnose what's going wrong. – Trevor Powell May 21 '17 at 1:33

If you do not put a #version NNN pragma at the top of your shader it will compile according to GLSL 1.10 which does not supports the f suffix.
• If you don't use the directive #version the shader will be compiled as version 1.1 which does not support the f suffix. And newer drivers tend to enforce this. – Stephane Hockenhull May 21 '17 at 1:51


text:
# A representation of a finite group where every nonzero vector has a trivial stabilizer [duplicate]

What are the finite groups which admit a non-zero representation in char 0 where every non-zero vector has stabilizer equal to $\left<1\right>$? Cyclic groups of prime order is one obvious class. Is there anything else?

• All nontrivial cyclic groups, ${\rm SL}(2,5)$ and its subgroups. – Derek Holt Jul 17 '15 at 8:27
• Also generalized quaternion groups. – Jeremy Rickard Jul 17 '15 at 9:16
• A sylow $2$-subgroup would have to be cyclic or generalized quaternion, which restricts the structure. I wonder if there are any interesting odd order examples. – Derek Holt Jul 17 '15 at 9:20
• After reading Geoff Robinson's answer, I found the earlier post, which is mathoverflow.net/questions/191769 So perhaps this question should be regarded as a duplicate? – Derek Holt Jul 17 '15 at 10:27
• @Derek Holt: I agree that there is not much to be learned from this question which is not covered by the earlier question and its answers. – Geoff Robinson Jul 17 '15 at 10:41

I think these groups have appeared on MO before. A finite group $H$ has such a representation in characteristic zero if and only if $H$ occurs as a Frobenius complement. This is "well-known folklore" and appears in a book by D. Passman for example.

First, if $H$ is Frobenius complement in a Frobenius group $G$ with Frobenius kernel $K$, any non-trivial minimal $H$-invariant subgroup $V$ of $K$ is an elementary Abelian $q$-group for some prime $q$ not dividing $|H|$, since $|H|$ and $|K|$ are comprime. Also $H$ acts faithfully on $V$. We can pass to an algebraic closure of ${\rm GF}(q)$ and lift the representation of $H$ to characteristic zero, and we obtain a complex representation of $H$ such that all non-identity elements act without the eigenvalue $1$.

Conversely, if $H$ has a complex representation with this last property, then we can reduce the associated module (mod $q$) for some prime $q$ not dividing $|H|$. Then we easily obtain a semidirect product $VH$ with $V$ an elementary Abelian normal $q$-subgroup such that $H$ is a Frobenius complement.

The structure of a (finite) Frobenius complement $H$ is reasonably well understood. For example, Burnside knew that if $p$ and $q$ are different prime divisors of $H$, every subgroup of $H$ of order $pq$ is cyclic. As mentioned in comments, all Sylow subgroups of $H$ are cyclic or (generalized) quaternion.

The only perfect Frobenius complement is ${\rm SL}(2,5).$ There is a Frobenius complement of order $63$ with center of order $3$.

Later edit: This last group has a complex irreducible representation of degree $3$ in which no non-identity element has an eigenvalue $1$. In general, a Frobenius complement of odd order is metacyclic.

Even later edit: Here is a quick direct proof that any finite non-trivial group $G$ which has all subgroups normal necessarily has an irreducible complex representation (which may not be faithful) of the type in the question: take $\chi$ to be an irreducible non-trivial complex character of $G$. Let $N = {\rm ker} \chi$. Then by induction, we may suppose that $N = 1$, as $G/N$ has all its subgroups normal. Hence we may suppose that $\chi$ is faithful. For any $g \in G^{\#}$, Clifford's theorem tells us that ${\rm Res}^{G}_{\langle g \rangle}(\chi)$ is a sum of $G$-conjugate irreducible characters of $\langle g \rangle$, since $\langle g \rangle \lhd G.$ None of these can be the trivial character (or they would all be trivial, since they are all $G$-conjugate, and that would put $g$ in ${\rm ker}\chi$). Hence $g$ acts without the eigenvalue $1$ in the representation affording $\chi$.


text:
# How might airships be made using 18th century technology?

Using only what is available in the 18h century, across any culture, what might airships look like in such a culture, assuming that an inventor used the resources he had to create one.

• Sounds like that works as a complete (and high-quality) answer, @AlexP! Why not post it as such? – Shokhet Apr 24 '17 at 3:21
• what do you mean in term airship? Wiki assumes Aerostat as type of airship. Is it appropriate for you? – ADS Apr 24 '17 at 7:34
• @ADS: You have it backwards. Airships are a kind of aerostat; not all aerostats are airships. Specifically, airship are dirigible aerostats. Like all aerostats, they derive their lift from buoyant gas; unlike balloons, they have engines and control surfaces which enable the crew to steer them and fly on a preset course. – AlexP Apr 24 '17 at 8:00
• A Napoleonic style world and warfare with flying ships is such a vividly damn cool concept for a world that basically - who gives a frick how!? Get a few things invented a bit quicker by the guild of alchemists and metallurgical wotsists and just hand-wave it the hell in! – Grimm The Opiner Apr 24 '17 at 13:58
• The hot-air balloon was invented in 1783 (according to wikipedia anyway). So it would look like a hot air balloon! – colmde Apr 24 '17 at 16:09

Sorry but no. No aluminium and no internal combustion engines means no airships.

• You must have aluminium -- there is no substitute for its combination of strength and lightness; and to smelt aluminium you need copious amount of electric power, which was not available in the 18th century.

The Hall–Héroult process for smelting aluminium was invented in 1886; before that aluminium was more expensive than gold and silver. As an anecdote, emperor Napoleon III of France "is reputed to have held a banquet where the most honored guests were given aluminium utensils, while the others made do with gold", or at least so says Wikipedia.

• You must have internal combustion engines -- there is no substitute for their high specific power. Steam engines are too heavy; they need large high-pressure boilers, they must carry the water with them in addition to the engine and the fuel, and open flames don't mix well with hydrogen (or they mix rather too well, depeding on the point of view).

The first primitive internal combustion engines were invented right at the end of the 18th century, with practical engines appearing towards the middle of the 19th. The Diesel engine (which was actually used on actual airships) was invented in 1892.

Some comments suggest that wood may be used to make the structure of airships. There are after all historical examples of airships with wooden structures. The first problem is that, as the linked Wikipedia article says, "the airships became structurally unstable when water entered the airship's imperfectly waterproofed envelope, [...] during wet weather operations". The second problem is that [above a certain size] "the superiority of aluminum (and later duralumin) in tension was more important than the superiority of wood in compression". It's the same as with airplanes: small airplanes can be made of wood, larger airplanes cannot; for airships this is even more important, because in order to be actually useful airships must be very large.

(I have converted the comment into an answer as advised by user Shokhet).

• but first airplanes were made with wood. And what about aerostats? – ADS Apr 24 '17 at 7:27
• @ADS: Aerostats in general are of course possible in the 18th century. My answer refers to airships. The Montgolfier brothers made the first ascension in a balloon in 1783. Aeroplanes are aerodynes, they derive their lift from the flow of air over airfoils; there are sailplanes made of wood and fabric even today. – AlexP Apr 24 '17 at 8:01
• there is no substitute for its combination of strength and lightness Substitutes might be hard to obtain for the given time but so was aluminium. There are in fact several substitutes available: CFRP, fiberglas, aramid reinforced plastic, Ochroma wood, titanium, magnesium alloys and even steel all have a better or comparable specific strength. In fact aluminium already got replaced especially by CFRP in a wide varity of applications (e.g. aircraft, rocketry or sport cars) limited only by the current cost. – Christoph Apr 24 '17 at 11:20
• The first Schütte-Lanz - Airships had wooden skeletons. I do agree that power sources would be a problem, though. – Burki Apr 24 '17 at 12:16
• @AlexP You should explain why you think the materials available did not suit the needs (a wooden one actually could have worked noone wants to fly during rain). You must have aluminium is as wrong as it is absolute. – Christoph Apr 24 '17 at 13:22

The first demonstration of a prototype balloon was in 1709 (Father Bartolomeu de Gusmão).

The world's first air force was founded 1793 - French Aerostatic Corps

Option 1: Take Father Francesco Lana de Terzi's vacuum design (1673), and permit money and time to be focused upon it.

Option 2: A variant of Lieutenant Jean Baptiste Marie Meusnier's balloon ship with bird-like attachments (1785).

Option 3: A glider type of ship (Swedenborg, 1716), taking advantage of the ability to dynamically fly (which would have to be learned).

Option 4: A combination balloon glider - that uses its ability to change altitudes to gain switch direction and engage in dynamic flying with fixed wings.

All of these are possible in the 18th century - they just needed funding and focus to make them happen.

• Spending sweat and treasure of vacuum airships would result in a prompt understanding of atmospheric pressure and the need to conterbalance it with a gas. And gliders are not airships, they are aeroplanes. – AlexP Apr 24 '17 at 21:21

Steam engines have problems of weight once you include the boiler - and 18th century materials technology REALLY wasn't up to the sort of pressures you need in a flash steam (or water tube) boiler.

However, there has been at least one pedal-powered airship!

Make that at least two ... the White Dwarf, built in 1984

piloted by Bryan Allen, famous for flying the Gossamer Albatross across the Channel in 1979. I believe White Dwarf still has the world record flight (58 miles) for pedal powered airships, and cruises at 6 or 7 knots.

and a French one, on which Stephane Rousson apparently failed to cross the Channel in 2008.

It's not totally beyond belief that one could be built using 18th century materials - very light woodwork or bamboo, silk, and hydrogen gas - though performance might be less than modern standards.

• The structure of the White Dwarf was made of aluminium... – AlexP Apr 24 '17 at 21:25
• ... and it allegedly had a 5G loading factor. As the volume of Al iwas relatively small, it's highly likely that a wooden structure wouldn't kill the project. – Brian Drummond Apr 24 '17 at 21:29
• Will silk hold Hydrogen gas? – Taemyr Apr 25 '17 at 7:45
• Silk isn't gas tight. I think you'll need goldbeaters skin too,as another answer said. I'd forgotten that term. – Brian Drummond Apr 25 '17 at 8:00

How might airships be made using 18th century technology?

I think the answer is: using 1920-1930 aerodynamics and flight mechanics knowledges, late 18th century steam engines knowledges, wood and fabric.

Remember Clement Ader's 1890 steam engine produced 20hp for 51kg, which is 2.5kg/hp, while Wright brothers 1903 internal combustion engine produced 12hp for 75kg, which is 6.2kg/hp.

An 18th century Watt's double action piston steam engine, made out of steel, could have produced enough power. Even if it was 20hp for 150kg (7.5kg/hp)

Put such an engine on (let's say) a 1930 Piper Cub, or a Fiesler Storch, and it will fly. A Piper Cub is mostly made of wood and fabric, which was doable in the 18th century.

Main problem was the lack of knowledges in aerodynamics, but if guys like Otto Lilienthal, Wright brothers and Gerhard Fieseler were born in 1750, and met an other steam engine genius, then first human heavier than air flight could have been achieved in late 18th century.

• But that 1890 steam engine required 1890s technology for high-grade steel and precision machining. It would have been utterly impossible to construct that a century earlier, because that quality of metal and machining did not exist, and could never have existed because it built on continuous advances over that century. The state of the art for lightweight steam engines by the end of the 18th century was the kind of engine that went into Puffing Billy. So even if you had the aeronautical knowledge, you still wouldn't have a viable engine. – Graham Apr 24 '17 at 12:51
• Not to put too fine a point on it, it's not just Lilienthal and Newcomen getting together. You also need Bessemer, Mushet and all the engineers who developed tool steel production, and spent decades investigating the properties of various alloys. And then you need the myriad nameless engineers who invented proper metalworking lathes, drill presses and so on over the 19th century, and you need the precision measurement techniques required (and enabled) to go along with it. – Graham Apr 24 '17 at 13:08
• @Graham Nice input I agree, precision machining and tools to do so would have been essential, at this time. But if you think "takeoff and land" or 3 minutes operation time, some leather sealed piston could survive. – qq jkztd Apr 24 '17 at 13:32
• The Piper Cub is an aeroplane. The question asks for airships. – AlexP Apr 24 '17 at 13:59
• Don't forget what you need to run the engine. The mass of high-end steam engines wasn't the only problem - you also need to account for the water. You'd need a closed-cycle steam engine for any duration flight, and those are a lot less mass-efficient than open-cycle engines. – Luaan Apr 24 '17 at 14:06

They might be able to build zeppelins, as they do not require a lot of technology to make. They could be made with layers of textile, which has been made airtight with beeswax. Or as dot_Sp0T commented, use goldbeater's skin to reduce the need for beeswax (I think it will still be needed to seal up the seams).


text:
SEARCH HOME
 Math Central Quandaries & Queries
 Question from Kate, a parent: My daughter was given a math question, which we did together. However, when her class took it up in school, there were different answers among the students. The question is: A small toad is sitting at the bottom of the stairs. He wants to get to the 10th step, but is having some difficulty. He jumps up 2 steps and then back 1 each time. How many jumps will he take to reach the 10th step? The 4th grade students came up with answers such as 10, 26 etc. My daughter and I got 17. How would you interpret this question?

We have two responses for you

Kate,

you need to focus on what happens every time he jumps (except possibly the last time). When he first jumps he goes up two but slides back one for a net gain of one step. Thus after his 1st jump he's on step 1. Similarly he will be on step 2 after his 2nd jump. And so on for a while. The crux of the matter is what happens when he makes a leap on the 9th day - he'll be starting from the 8th step. He will leap and reach the 10th step and slide back one - now semantics come into the problem, has he reached the 10th step at this point or not? In this sense the problem is a bit vague but I would tend to think he has 'reached' the 10th step. Otherwise it would take him a 10th leap to make it to the 10th step, i.e. to finish up on the 10th step. This problem is often stated in terms of jumping out of a well in which case I would certainly say that on the 9th day he's out of the well. If it's a long staircase in your problem then I would listen to an argument that reaching the 10th step means ending up on it.

Hope this helps,

Penny

Hi Kate.

The way I read this is that the toad starts below step #1 and each time he moves between two steps (either going up or going down) is a jump.

So I'd say the following sequence happens:

On the first jump, the toad reaches the 2nd step.
(On the second jump, he jumps to the 1st step).
On the third jump, the toad reaches the 3rd step.
(On the fourth jump, he jumps back to the 2nd step).

...

On the fifteenth jump, the toad reaches the 9th step.
(On the sixteenth jump, he jumps back to the 8th step).
On the seventeenth jump, the toad reaches the 10th step.

So you are right: 17 jumps.

Think of it as two interwoven sequences:

Odd numbered jumps end on floors 2, 3, 4, 5, 6, 7, 8, 9, 10
Even numbered jumps end on floors 1, 2, 3, 4, 5, 6, 7, 8, 9.

So the mixed sequence is 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10.

Cheers,
Stephen La Rocque.

Math Central is supported by the University of Regina and The Pacific Institute for the Mathematical Sciences.