Am 18.12.2012 13:37, schrieb Jean Dubois: > I have trouble with the code beneath to make an array with equally > spaced values > When I enter 100e-6 as start value, 700e-6 as end value and 100e-6 I > get the following result: > [ 0.0001 0.00022 0.00034 0.00046 0.00058 0.0007 ] > But I was hoping for: > [ 0.0001 0.0002 0.0003 0.0004 0.0005 0.0006 0.0007] > It works correctly for other values like 1,7,1 but not for 0.1,0.7,0.1 > then again for 0.01,0.07,0.01 > > What I find strange is that for the 1st example "1+abs(float(endvalue)- > float(startvalue))/float(incr)" gives 7.0 but int() of this value > gives 6 > can someone provide help with this issue? > thanks > jean > > #!/usr/bin/python > import math > import numpy as np > print "Enter start value as a float (e.g. 0.001) or in scientific > notation (e.g. 1e-3): ", > startvalue = raw_input() > print "Enter end value: ", > endvalue = raw_input() > print "Enter step: ", > incr = raw_input() > #nom = number of measurements > nom=int(1+abs(float(endvalue)-float(startvalue))/float(incr)) > array=np.linspace(float(startvalue), float(endvalue), float(nom)) > print "Array with current values: ",array
The Problem is the accuracy/precision of floating point operations Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 100e-6 #start >>> b = 700e-6 #end >>> c = 100e-6 #incr >>> 1+(b-a)/c 6.999999999999999 and the fact that int() only takes the integer part of a floating point number. >>> int(1+(b-a)/c) 6 So you have to make a more detailed decision about the number of points in the case that (end-start)/incr is not exactly an integer which it will almost never be. The np.arange(a,b,c) function chooses a simple rule: give a list of numbers a + k * c with k running from 0 to the highest integer with a + k * c < b. >>> np.arange(a,b,c) array([ 0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006]) You can get your desired list by adding some epsilon to the value of b. Just make sure your epsilon is quite small compared to c. >>> np.arange(a,b+1e-15,c) array([ 0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007]) Greetings -- http://mail.python.org/mailman/listinfo/python-list