# How to determine if an rgb color value (x,y,z) is within a gradient between to other rgb values

Say I have two colors

color1=[red:255, green:0, blue:0 ]

color2:[red:0,green:255,blue:0 ]


Imagine a gradient between those two colors, with color1 on the far left slowly transitioning to color2 on the right.

How could I determine if a third color was in that color gradient band?

Right now I determine it the long way by comparing ratios of change in a procedural way.

Is there an equation that would simplify this?

Step 1: Determine how far along the third color is, in the red axis.

Step 2: Check to see if the third color is equally far along in the green and blue axes.

Explicit formulas:

Suppose the three red color values are $R_1, R_2, R_3$. We set $$\lambda_R=\frac{R_3-R_1}{R_2-R_1}$$ This constant $\lambda_R$ should be between $0$ and $1$; otherwise we just answer "NO".

We can compute $\lambda_G$, $\lambda_B$ for the other two colors similarly. If the three constants agree (up to rounding error) we answer "YES"; otherwise "NO". The only thing to be careful about is if $R_1=R_2$; we don't want to divide by zero, so we just separately check to see if $R_3=R_1$ or not (as in the given example,for blue).

It depends somewhat on how the gradient is carried out. The most likely case is that is is a simply a linear function $$\mathbf{c}(t)=\langle 255,0,0\rangle + t\langle -255,255,0\rangle.$$ for $t\in[0,1]$ notice that $\mathbf{c}(0)$ is the vector corresponding to color one and $\mathbf{c}(1)$ is color two.

The important thing to notice here is that the second summand always adds the same amount to the second coordinate as it removes from the first. Therefore, you could use this simple criteria: a color $\langle a,b,c\rangle$ is in the gradient if

1. $c=0$
2. $a+b=255$

Edit: I'll round out my answer just to make it a bit more general. If you are given two colors $\alpha=\langle r_1,g_1,b_1\rangle$ and $\beta=\langle r_2,g_2,b_2\rangle$, then every color on the straight-line gradient between them can be realized as a value of the function $$\mathbf{c}(t)=\alpha+t(\beta-\alpha)=\langle r_1,g_1,b_1\rangle+t\langle r_2-r_1,g_2-g_1,b_2-b_1\rangle$$ again, as $t$ ranges over the interval $[0,1]$. As before, $\mathbf{c}(0)=\alpha$ and $\mathbf{c}(1)=\beta$.

Now if you have a vector $\gamma=\langle r_3,g_3,b_3\rangle$ and you want to determine whether this color lies on the the gradient, you would have to see if there is a $t\in[0,1]$ that satisfies the equation $$\gamma=\alpha+t(\beta-\alpha)$$ which can be checked using the $\lambda_i$ used in @vadim123's answer.