Plot output differences between python and julia - python-3.x
I am trying to use julai as main language for my work. But I find that this plot is different than python (Which outputs the right plot)
Here is the python code and output
import numpy as np
import math
import matplotlib.pyplot as plt
u = 9.27*10**(-21)
k = 1.38*10**(-16)
j2 = 7/2
nrr = 780
h = 1000
na = 6*10**(23)
rho = 7.842
mgd = 157.25
a = mgd
d = na*rho*u/a
m_f = []
igd = 7.0
for t in range(1,401):
while True:
h1 = h+d*nrr*igd
x2 = (7*u*h1)/(k*t)
x4 = 2*j2
q2 = (x4+1)/x4
m = abs(7*(q2*math.tanh(q2*x2)**-1 - (1/x4)*math.tanh(x2/x4)**-1))
if abs(m - igd) < 10**(-12):
break
else:
igd = m
m_f.append(abs(m))
plt.plot(range(1,401), m_f)
plt.savefig("Py_plot.pdf")
and it gives the following right plot
The right plot as expected
But when I do the same calculations in julia it gives different output than python, here is my julia code
using Plots
u = 9.27*10^(-21)
k = 1.38*10^(-16)
j2 = 7/2
nrr = 780
h = 1000
na = 6*10^(23)
rho = 7.842
mgd = 157.25
a = mgd
d = na*rho*u/a
igd = 7.0
m = 0.0
m_f = Float64[]
for t in 1:400
while true
h1 = h+d*nrr*igd
x2 = (7*u*h1)/(k*t)
x4 = 2*j2
q2 = (x4+1)/x4
m = 7*(q2*coth(rad2deg(q2*x2))-(1/x4)*coth(rad2deg(x2/x4)))
if abs(abs(m)-igd) < 10^(-10)
break
else
igd = m
end
end
push!(m_f, abs(m))
end
plot(1:400, m_f)
and this is the unexpected julia output
unexpected wrong output from julia
I wish for help....
Code:
using Plots
const u = 9.27e-21
const k = 1.38e-16
const j2 = 7/2
const nrr = 780
const h = 1000
const na = 6.0e23
const rho = 7.842
const mgd = 157.25
const a = mgd
const d = na*rho*u/a
function plot_graph()
igd = 7.0
m = 0.0
trange = 1:400
m_f = Vector{Float64}(undef, length(trange))
for t in trange
while true
h1 = h+d*nrr*igd
x2 = (7*u*h1)/(k*t)
x4 = 2*j2
q2 = (x4+1)/x4
m = abs(7*(q2*coth(q2*x2)-(1/x4)*coth(x2/x4)))
if isapprox(m, igd, atol = 10^(-10))
break
else
igd = m
end
end
m_f[t] = m
end
plot(trange, m_f)
end
Plot:
Changes for correctness:
Changed na = 6.0*10^(23) to na = 6.0e23.
Since ^ has a higher precedence than *, 10^23 is evaluated first, and since the operands are Int values, the result is also an Int. However, Int (i.e. Int64) can only hold numbers up to approximately 9 * 10^18, so 10^23 overflows and gives a wrong result.
julia> 10^18
1000000000000000000
julia> 10^19 #overflow starts here
-8446744073709551616
julia> 10^23 #and gives a wrong value here too
200376420520689664
6.0e23 avoids this problem by directly using the scientific e-notation to create a literal Float64 value (Float64 can hold this value without overflowing).
Removed the rad2deg calls when calling coth. Julia trigonometric functions by default take radians, so there's no need to make this conversion.
Other changes
Marked all the constants as const, and moved the rest of the code into a function. See Performance tip: Avoid non-constant global variables
Changed the abs(m - igd) < 10^-10 to isapprox(m, igd, atol = 10^-10) which performs basically the same check, but is clearer and more flexible (for eg. if you wanted to change to a relative tolerance rtol later).
Stored the 1:400 as a named variable trange. This is just because it's used multiple times, so it's easier to manage as a variable.
Changed m_f = Float64[] to m_f = Vector{Float64}(undef, length(trange)) (and the push! at the end to an assignment). If the size of the array is known beforehand (as it is in this case), it's better for performance to pre-allocate it with undef values and then assign to it.
Changed u and k also to use the scientific e-notation, for consistency and clarity (thanks to #DNF for suggesting the use of this notation in the comments).
Related
getting marginal effect post-estimation for nested logit using R mlogit package
I have estimated nested logit in R using the mlogit package. However, I encountered some problems when trying to estimate the marginal effect. Below is the code I implemented. library(mlogit) # data data2 = read.csv(file = "neat_num_energy.csv") new_ener2 <- mlogit.data( data2, choice="alter4", shape="long", alt.var="energy_altern",chid.var="id") # estimate model nest2 <- mlogit( alter4 ~ expendmaint + expendnegy | educ + sex + ppa_power_sp + hu_price_powersupply + hu_2price +hu_3price + hu_9price + hu_10price + hu_11price + hu_12price, data = data2, nests = list( Trad = c('Biomas_Trad', 'Solar_Trad'), modern = c('Biomas_Modern', 'Solar_Modern') ), unscaled=FALSE) # create Z variable z3 <- with(data2, data.frame( expendnegy = tapply(expendnegy, idx(nest2,2), mean), expendmaint= tapply(expendmaint, idx(nest2,2), mean), educ= mean(educ), sex = mean(sex), hu_price_powersupply = mean(hu_price_powersupply), ppa_power_sp = mean(ppa_power_sp), hu_2price = mean(hu_2price), hu_3price = mean(hu_3price), hu_9price = mean(hu_9price), hu_10price = mean(hu_10price), hu_11price = mean(hu_11price), ppa_power_sp = mean(ppa_power_sp), hu_12price = mean(hu_12price) )) effects(nest2, covariate = "sex", data = z3, type = "ar") #> ** Error in Solve.default (H, g[!fixed]): Lapack routine dgesv: #> system is exactly singular:U[6,6] =0.** My data is in long format with expendmaint and expendnegy being the only alternative specific while every other variable is case specific. altern4 is a nominal variable representing each alternative
SymPy : Cancel out unnecessary variables and coefficients
I have an expression like : b = IndexedBase('b') k = IndexedBase('k') w = IndexedBase('w') r = IndexedBase('r') z = IndexedBase('z') i = symbols("i", cls=Idx) omega = symbols("omega", cls=Idx) e_p = (-k[i, omega]*r[i]/w[i] + k[i, omega]*r[i]/(b[omega]*w[i]))**b[omega]*k[i, omega]*r[i]/(-b[omega]*k[i, omega]*k[i, omega]**b[omega]*r[i]*z[omega]/w[i] + k[i, omega]*k[i, omega]**b[omega]*r[i]*z[omega]/w[i]) e_p = simplify(e_p) print(type(e_p)) print(e_p) <class 'sympy.core.mul.Mul'> -(-(b[omega] - 1)*k[i, omega]*r[i]/(b[omega]*w[i]))**b[omega]*k[i, omega]**(-b[omega])*w[i]/((b[omega] - 1)*z[omega]) So k[i, omega] should be canceled out when I use simplify() function but do nothing. How can I get rid of unnecessary variables and coefficients?
Set variable to Memory Address in Python 3.5
How would I convert these lines (originally python-2.7) to Python-3.5: DELETE = 0x00010000L READ_CONTROL = 0x00020000L WRITE_DAC = 0x00040000L WRITE_OWNER = 0x00080000L SYNCHRONIZE = 0x00100000L STANDARD_RIGHTS_REQUIRED = 0x000F0000L STANDARD_RIGHTS_READ = READ_CONTROL STANDARD_RIGHTS_WRITE = READ_CONTROL STANDARD_RIGHTS_EXECUTE = READ_CONTROL STANDARD_RIGHTS_ALL = 0x001F0000L SPECIFIC_RIGHTS_ALL = 0x0000FFFFL These lines just retrun Syntax error on python-3.5
Python 3 no longer has a distinction between a long and regular int. Just remove the L at the end of the hex literals and you are good to go: >>> STANDARD_RIGHTS_ALL = 0x001F0000 >>> STANDARD_RIGHTS_ALL 2031616 >>> hex(STANDARD_RIGHTS_ALL ) '0x1f0000'
Strings in Matlab table
I have a string of alphabets e.g. S = ['a';'b';'c';'d';'e']; and I want to put it in column 3 in the table: table(:,1) = M1; table(:,2) = d1; disp(table) M1 and d1 are 5 X 1 matrices of numbers each.
You could think to do as follows: r = {M1, d1, S}; or r = {M1; d1; S}; EDIT you may also do this: M1 = rand(5,1); d1 = rand(5,1); S = ['a';'b';'c';'d';'e']; y = arrayfun(#(i) {M1(i), d1(i), S(i)'},1:5,'UniformOutput',false); res = cat(1,y{:}); I'd suggest this approach to solve your question.
Updating a string inside a callback
The following code is a graphic rendering of the Earth globe spinning eastward. I have two push buttons, Spin and Stop. Both share the same callback function, hAnimaCallback. In particular, this latter does not work. I pretend to use the strings (names) of the push buttons to create a switch that stops the movement. However, I can not get to change the string name inside the while loop and I do not understand why my method is wrong. function example fh = figure('Menu','none','Toolbar','none','Units','characters'); T = 0:pi/100:2*pi; Y = zeros(numel(T),3); Y(:,1) = 7000*cos(T); Y(:,2) = 7000*sin(T); hPanAni = uipanel('parent',fh,'Units','characters','Position',... [22.6 10.4 53 23],'title','Controls','FontSize',11,... 'FontAngle','italic','FontWeight','bold'); hIniAni = uicontrol(hPanAni,'Style','pushbutton','Units','normalized',... 'Position',[0.14 0.64 0.5 0.12],'String','Spin',... 'FontSize',10,'Callback',#hAnimaCallback); hFinAni = uicontrol(hPanAni,'Style','pushbutton','Units','normalized',... 'Position',[0.14 0.26 0.5 0.12],'String','Stop',... 'FontSize',10,'Callback',#hAnimaCallback); hPantSim = uipanel('Parent',fh,'Units','characters',... 'Position',[107.87 8 157.447 42],'BorderType','none','title',... 'Screen','FontSize',11,'FontAngle','italic',... 'FontWeight','bold'); hPantSimInt = uipanel('Parent',hPantSim,'Units','normalized','Position',... [0 0 1 1],'BorderType','line','BackgroundColor','black'); ah4 = axes('Parent',hPantSimInt,'Units','normalized','Position',... [0 0 1 1],'Color','none','Visible','off','DataAspectRatio',... [1 1 1],'NextPlot','add'); rotate3d(ah4); hgrot = hgtransform('Parent',ah4); Resf = 6378; maptext = imread('tierra.jpg'); [X, map] = rgb2ind(maptext,128); [x,y,z] = sphere(50); x = Resf*x; y = Resf*y; z = Resf*z; props.FaceColor= 'texture'; props.EdgeColor = 'none'; props.Parent = hgrot; props.Cdata = flipud(X); % it is necesary to do this for getting the % appropiate image on the sphere hsurf = surface(x,y,z,props); colormap(map); axis equal; view([71 14]); set(gcf,'Renderer','opengl') drawnow; line('parent',ah4,'XData',Y(:,1),'YData',Y(:,2),'ZData',... Y(:,3),'Color','red','LineWidth',2); line('parent',ah4,'XData',Y(end,1),'YData',Y(end,2),... 'ZData',Y(end,3),'Marker','o','MarkerSize',6,'MarkerFaceColor','b'); axis square equal vis3d; view(3); handles.XLim = get(ah4,'XLim'); handles.YLim = get(ah4,'YLim'); handles.ZLim = get(ah4,'ZLim'); xmin = handles.XLim(1); ymin = handles.YLim(1); zmin = handles.ZLim(1); xmax = handles.XLim(2); ymax = handles.YLim(2); zmax = handles.ZLim(2); set(ah4, 'XLim', [xmin xmax],'YLim', [ymin ymax],'Zlim',[zmin zmax]); az = 0; function hAnimaCallback(hObject,evt) while (ishandle(fh)) state = get(hObject,'String'), % state should change between the states of % Spin and Stop but this does not occur if (strcmp(state,'Stop')) break; else az = az + 0.01745329252; set(hgrot,'Matrix',makehgtform('zrotate',az)); drawnow; end end end end
It seems like you are running into some kind of race condition because of the repeated drawnow calls in the while loop. The state changes to Stop, when you press the Stop button, but it is to quick to notice. Basically, the while loop is running as fast as MATLAB can run. Instead of drawnow using a pause(0.1) command seems to work (with a little bit code logic changes): az = 0; spin = false; function hAnimaCallback(hObject,~) state = get(hObject,'String') if strcmp(state, 'Spin') spin = true; else spin = false; end while (spin) az = az + 0.01745329252; set(hgrot,'Matrix',makehgtform('zrotate',az)); pause(0.1); end end