Wrong output in python, c# version works fine - python

# your code goes here
def lagrange(x0, xlist,ylist):
wynik =float(0)
if (len(xlist)!=len(ylist)):
raise BufferError("Rozmiary list wartosci x i y musza byc takie same!")
for i in range(len(xlist)):
licznik=float(1)
mianownik = float(1)
for j in range(len(xlist)):
if (i!=j):
licznik=licznik*(x0-xlist[j])
mianownik=mianownik*(xlist[i]-xlist[j])
wynik=wynik+((licznik/mianownik)*ylist[i])
return wynik
x=[2.0,4.0,5.0,6.0 ]
y=[0.57672, -0.06604, -0.32757, -0.27668]
print ("Lagrange polynomial for point 5.5 is %d" % lagrange(5.5, x, y))
Why do I get answer 0 after I run it? When rewritten to c# and run with the same data it outputs answer -0.3539. Seems to me like casting / rounding error but I'm struggling to find it without debugger.
I am completely new to python, I'm using basic IdleX on windows to code it.

The problem is not your function, it’s the printing.
The formatter %d is a signed integer decimal. So if you have -0.354 as a result, it gets rounded to 0.
Instead, print using %f:
>>> print ("Lagrange polynomial for point 5.5 is %f" % lagrange(5.5, x, y))
Lagrange polynomial for point 5.5 is -0.353952

Related

Float divisions returning wierd results

Im trying to do a project and for some reason the same divisions give me different results. I am trying to check if 2 divisions are equal and give me the same results but When I try 5.99/1 and 0.599/0.1 the script says that they are different while they are supposed to return the same results. I figured out what the problem is that 5.99/1 = 5.99 and 0.599/0.1 = 5.989999999999999but I cant find a fix for this.
You can find the reason in this answer: https://stackoverflow.com/a/588014/11502612
I have written a possible solution for you:
Code:
a = 5.99 / 1
b = 0.599 / 0.1
a_str = "{:.4f}".format(5.99 / 1)
b_str = "{:.4f}".format(0.599 / 0.1)
print(a, b)
print(a_str, b_str)
print(a == b)
print(a_str == b_str)
Output:
>>> python3 test.py
5.99 5.989999999999999
5.9900 5.9900
False
True
As you can see below I have converted the result of division to a formatted string and I check them instead of default floating type.

format() function is always returning "0.00"

I have some calculation that I am running that would provide a double/float back:
a = float(4)
b = float(56100)
c = a / b
Now when run the script, I get this:
7.1301e-05
I just need to format this response so that I get 7.13. But when I try to do this I get 0.00:
percentage_connections_used = float(a) / float(b)
percentage_float = float(percentage_connections_used)
print(format(percentage_float, '.2f'))
I can't seem to figure out why it would return 0 when trying to format it. Can someone possibly tell me what is going on? This is Python 2.7
I think your format is correct, but when you try to round to 2 decimal places It actually rounds to 0.00.
7.8125e-05 = 0.000078125
When rendered as 2 decimals, you get 0.00.
You could do a little string manipulation to parse out the 7.8125 figure by using:
d = float(str(c).split('e')[0])
It's a little verbose, though, and maybe someone in the community can do better.
By the way, I get 7.1301...e-05 when I run a/b.
7.8125e-05 is the same as 0.000078125 so formatting it with only two decimal points gives you 0.00. You could do '.7f' which would get you 0.0000713. If you want it to output in scientific notation, you should do that explicitly. Try this:
a = float(4)
b = float(56100)
c = a / b
print("{:.2e}".format(c))

running matlab .m file using python

I have a matlab file (.m) and I want to run this file using python. I do not have matlab on my ubuntu system. Can I still run the matlab file?
isomonotone.m
% Checks vector v for monotonicity, and returns the direction (increasing,
% decreasing, constant, or none).
%
% Meaning of parameter tol:
% - if tol==0, check for non-increasing or non-decreasing sequence (default).
% - if tol>0, allow backward steps of size <= tol
% - if tol<0, require forward steps of size >= tol
%
% Inputs
% v: vector to check for monotonicity
% tol: see above
%
% Outputs
% b: a bitfield indicating monotonicity. Can be tested as follows:
% bitand(b,1)==true --> v is increasing (within tolerance)
% bitand(b,2)==true --> v is decreasing (within tolerance)
% bitand(b,3)==true --> v is both increasing and decreasing
% (i.e. v is constant, within tolerance).
% --------------------------------------------------------------------------
function b = ismonotone( v, tol )
if ( nargin < 2 )
tol = 0;
end
b = 0;
dv = diff(v);
if ( min(dv) >= -tol ) b = bitor( b, 1 ); end
if ( max(dv) <= tol ) b = bitor( b, 2 ); end
end
%!test assert(ismonotone(linspace(0,1,20)),1);
%!test assert(ismonotone(linspace(1,0,20)),2);
%!test assert(ismonotone(zeros(1,100)),3);
%!test
%! v=[0 -0.01 0 0 0.01 0.25 1];
%! assert(ismonotone(v,0.011),1);
%! assert(ismonotone(-v,0.011),2);
Can I run this file using python without having matlab on my ubuntu?
You can install Octave from the Ubuntu repository (or download and install the latest - that's more work)
Starting Octave in the directory where this file is, allows me to run the %! tests, thus:
octave:1> test ismonotone
PASSES 4 out of 4 tests
In fact the presence of those %! suggests that this file was originally written for Octave. Can someone confirm whether MATLAB can handle those doctest like lines?
edit - add interactive examples
octave:1> ismonotone(linspace(0,1,20))
ans = 1
octave:2> ismonotone(zeros(1,100))
ans = 3
Or from the linux shell
1424:~/myml$ octave -fq --eval 'ismonotone(linspace(0,1,20))'
ans = 1
For someone used to running Python scripts from the shell, Octave is more friendly than MATLAB. The startup overhead is much smaller, and the command line options are more familiar. In the interactive mode, doc opens a familiar UNIX info system.
Have you tried:
1. Small Matlab to Python compiler
2. LiberMate
3. Rewrite the code using SciPy module.
Hope this helps
Python cannot run Matlab programs natively. You would need to rewrite this in Python, likely using the SciPy libraries.

Porting IDL code, lindgen function to Python

Afternoon everyone. I'm currently porting over an IDL code to python and it's been plain sailing up until this point so far. I'm stuck on this section of IDL code:
nsteps = 266
ind2 = ((lindgen(nsteps+1,nsteps+1)) mod (nsteps+1))
dk2 = (k2arr((ind2+1) < nsteps) - k2arr(ind2-1) > 0)) / 2.
My version of this includes a rewritten lindgen function as follows:
def pylindgen(shape):
nelem = numpy.prod(numpy.array(shape))
out = numpy.arange(nelem,dtype=int)
return numpy.reshape(out,shape)
... and the ported code where k2arr is an array of shape (267,):
ind2 = pylindgen((nsteps+1,nsteps+1)) % (nsteps+1)
dk2 = (k2arr[ (ind2+1) < nsteps ] - k2arr[ (ind2-1) > 0. ]) / 2.
Now, the problem is that my code makes ind2 an array where, by looking at the IDL code and the errors thrown in the python script, I'm sure it's meant to be a scalar. Am I missing some feature of these IDL functions?
Any thoughts would be greatly appreciated.
Cheers.
My knowledge of IDL is not what it used to be, I had to research a little. The operator ">" in IDL is not an equivalent of python (or other languages). It stablishes a maximum, anything above it will be set to that value. Same goes for "<", obviously, it sets a minimum.
dk2 = (k2arr((ind2+1) < nsteps) - k2arr(ind2-1) > 0))
where k2arr is 266 and ind2 is (266,266) is equivalent to saying:
- (ind2+1 < nsteps) take ind2+1 and, in any place that ind2+1
is greater than nsteps, replace by nsteps.
- (ind2-1 > 0) take ind2-1 and, in any place that ind2-1 is
less than zero, put zero instead.
The tricky part is now. k2arr (266,) is evaluated for each of the rows of (ind2+1) and (ind2-1), meaning that if (ind2+1 < nsteps) = [1,2,3,...,nsteps-1, nsteps, nsteps] the k2arr will be evaluated for exactly that 266 times, one on top of the other, with the result being (266,266) array.
And NOW I remember why I stopped programming in IDL!
The code for pylindgen works perfectly for me. Produces an array of (267,267), though. IF k2array is a (267,) array, you should be getting an error like:
ValueError: boolean index array should have 1 dimension
Is that your problem?
Cheers

python - pretty print errorbars

I'm using python with numpy, scipy and matplotlib for data evaluation. As results I obtain averages and fitting parameters with errorbars.
I would like python to automatically pretty-print this data according to a given precision. For example:
Suppose I got the result x = 0.012345 +/- 0.000123.
Is there a way to automatically format this as 1.235(12) x 10^-2 when a precision of 2 was specified. That is, counting the precision in the errorbar, rather than in the value.
Does anyone know a package that provides such functionality, or would I have to implement this myself?
Is there a way to inject this into the python string formatting mechanism? I.e. being able to write something like "%.2N" % (0.012345, 0.0000123).
I already looked through the docs of numpy and scipy and googled around, but I couldn't find anything. I think this would be a useful feature for everyone who deals with statistics.
Thanks for your help!
EDIT:
As requested by Nathan Whitehead I'll give a few examples.
123 +- 1 ----precision 1-----> 123(1)
123 +- 1.1 ----precision 2-----> 123.0(11)
0.0123 +- 0.001 ----precision 1-----> 0.012(1)
123.111 +- 0.123 ----precision 2-----> 123.11(12)
The powers of ten are omitted for clarity.
The number inside the parenthesis is a shorthand notation for the standard error. The last digit of the number before the parens and the last digit of the number inside the parens have to be at the same decimal power. For some reason I cannot find a good explanation of this concept online. Only thing I got is this German Wikpedia article here. However, it is a quite common and very handy notation.
EDIT2:
I implemented the shorthand notation thing myself:
#!/usr/bin/env python
# *-* coding: utf-8 *-*
from math import floor, log10
# uncertainty to string
def un2str(x, xe, precision=2):
"""pretty print nominal value and uncertainty
x - nominal value
xe - uncertainty
precision - number of significant digits in uncertainty
returns shortest string representation of `x +- xe` either as
x.xx(ee)e+xx
or as
xxx.xx(ee)"""
# base 10 exponents
x_exp = int(floor(log10(x)))
xe_exp = int(floor(log10(xe)))
# uncertainty
un_exp = xe_exp-precision+1
un_int = round(xe*10**(-un_exp))
# nominal value
no_exp = un_exp
no_int = round(x*10**(-no_exp))
# format - nom(unc)exp
fieldw = x_exp - no_exp
fmt = '%%.%df' % fieldw
result1 = (fmt + '(%.0f)e%d') % (no_int*10**(-fieldw), un_int, x_exp)
# format - nom(unc)
fieldw = max(0, -no_exp)
fmt = '%%.%df' % fieldw
result2 = (fmt + '(%.0f)') % (no_int*10**no_exp, un_int*10**max(0, un_exp))
# return shortest representation
if len(result2) <= len(result1):
return result2
else:
return result1
if __name__ == "__main__":
xs = [123456, 12.34567, 0.123456, 0.001234560000, 0.0000123456]
xes = [ 123, 0.00123, 0.000123, 0.000000012345, 0.0000001234]
precs = [ 1, 2, 3, 4, 1]
for (x, xe, prec) in zip(xs, xes, precs):
print '%.6e +- %.6e #%d --> %s' % (x, xe, prec, un2str(x, xe, prec))
Output:
1.234560e+05 +- 1.230000e+02 #1 --> 1.235(1)e5
1.234567e+01 +- 1.230000e-03 #2 --> 12.3457(12)
1.234560e-01 +- 1.230000e-04 #3 --> 0.123456(123)
1.234560e-03 +- 1.234500e-08 #4 --> 0.00123456000(1235)
1.234560e-05 +- 1.234000e-07 #1 --> 1.23(1)e-5
For people that are still interested in this question, see the gvar library and here for an example of (at last part of) the desired behavior by the OP.
since x +- y is not a standard type (it could be seen as a complex with real and imaginary as x and y i guess, but that does not simplify anything...) but you can get full control over the presentation by creating a type and overriding the string function, i.e. something like this
class Res(object):
def __init__(self, res, delta):
self.res = res
self.delta = delta
def __str__(self):
return "%f +- %f"%(self.res,self.delta)
if __name__ == '__main__':
x = Res(0.2710,0.001)
print(x)
print(" a result: %s" % x)
you could naturally do something a bit more fancy inside the __str__ function...

Categories