[newbie] problem making equally spaced value array with linspace
news at blinne.net
Tue Dec 18 14:10:42 CET 2012
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?
> 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
> 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
and the fact that int() only takes the integer part of a floating point
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.
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.
array([ 0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007])
More information about the Python-list