Jacob
Jacob

Reputation: 135

Error in generating gradient

I have an error somewhere in this script that is supposed to generate a gradient. When the depth is equal to the difference the gradient is perfect, but floating point increments seem to screw it up. I've been staring at this code for so long I can't see the answer.

What's wrong with this code?

def interpolate(s, e, n):

start = list(s)
end = list(e)
incrementlst = []

for i in range(0,len(start)):
    diff = int(end[i]) - int(start[i])
    if diff == 0:
        increment = 0.0
    else:
        increment =diff/n


    incrementlst.append(increment)

return incrementlst

def incrementedValue(s, i, n):

    start = list(s)
    increment = list(i)
    n = n-1
    finallst = [0,0,0,0]
    if n < 1:
        return start

    for i in range(0,len(start)):
        finallst[i] = start[i] + (n*(increment[i]))


    return finallst

def formatIncrementedValue(l):

    cmykList = list(l)

    formattedString = str(int(round(cmykList[0], 0))) + " " + str(int(round(cmykList[1], 0))) + " " + str(int(round(cmykList[2], 0))) + " " + str(int(round(cmykList[3], 0)))
    return formattedString

# Get user inputs.
depth = int(ca_getcustomvalue ("depth", "0"))
start = ca_getcustomvalue("start", "0")
end = ca_getcustomvalue("end", "0")

startlst = start.split(" ")
startlst = [int(i) for i in startlst]
endlst = end.split(" ")
endlst = [int(i) for i in endlst]

# draw a line and incrementally change the pen colour towards the end colour 
colorlst = interpolate(startlst, endlst, depth)
for i in range(1,depth-1):
    color = formatIncrementedValue(incrementedValue(startlst, colorlst, i))

    #Draw line at correct offset in colour "color"

Upvotes: 0

Views: 101

Answers (1)

unwind
unwind

Reputation: 399803

This:

increment =diff/n

is doing integer division, so for instance if diff is 3 and n is 2, you get 1, not 1.5.

Make the expression float, to fix this:

increment = float(diff) / n

Upvotes: 2

Related Questions