i want to print the expression Xmin and Ymin as is without calculating the final value .
i,e with the values of I and J as 1,2,3,4,5
example
when I=1
Xmin= Xmin ((1 - 1)*10 + (1 - 1)*1)
is there a way to do it .. I tried the following code, but no luck:
int a, g;
a = 10;
g = 1;
for (int J=1; J<=5; J++)
{
for (int I = 1; I <= 5; I++)
{
string Xmin = Convert.ToString((I - 1)*a + (I - 1)*g);
string Ymin = Convert.ToString((J - 1) * a);
Debug.WriteLine("X=" + Xmin + "Y=" + Ymin);
}
}
You must use String.Format:
string Xmin = String.Format("({0} - 1)*{1} + ({0} - 1)*{2}", I, a, g);
Also, in .NET 3.5 you can use expression trees, but I daresay that would be a much more complicated solution than just using String.Format.
You need to put the expression in a string in order to do that, perhaps using String.Format
string Xmin = String.Format("Xmin=({0} - 1)*{1} + ({0} - 1)*{2}", I, a, g);
string Ymin = String.Format("Ymin=({0} - 1) * {1}", J, a);
Debug.WriteLine("X=" + Xmin + "Y=" + Ymin);
Related
I have a c# function that contains formula to calculate euclidean distance of some points. I got the point's position defined by R(rx,ry) and L(lx,ly).
at first, I tried to write the code like this:
double dRightLeft = Math.Sqrt((Math.Pow(rx - lx, 2) + Math.Pow(ry - ly, 2)));
it returns 0.0.
then I tried to split the variable to check where did I do wrong, like this:
double rl = (Math.Pow(rx - lx, 2) + Math.Pow(ry - ly, 2));
double dRightLeft = Math.Sqrt(rl);
the rl variable returns a valid value of its operation. but then when I tried to get the square root out of it, the dRighLeft variable still returns 0.0.
I tried both assigned and unassigned dRightLeft like this:
//assigned
dRightLeft = 0;
//unassigned
dRightLeft;
they both still returns 0.0 value.
here's my short but complete program where I get the rx, ry, lx, and ly value:
public Bitmap getDetectedImage()
{
int rx, rx, lx, ly, ...;
double dRightLeft = 0;
...
//righteyeloop
for (int x = fo.rightEye.X; x < (fo.rightEye.X + fo.rightEye.Width); x++)
{
for (int y = fo.rightEye.Y; y < (fo.rightEye.Y + fo.rightEye.Height); y++)
{ //segmentation...//
rPixel++;
result.byteImage[x, y].R = 0;
result.byteImage[x, y].G = 255;
result.byteImage[x, y].B = 0;
//to get the the first pixel detected//
if (rPixel == 1)
{
result.byteImage[x, y].R = 255;
result.byteImage[x, y].G = 0;
result.byteImage[x, y].B = 0;
rx = x + (fo.rightEye.Width / setting.featureWidth * setting.eyeHeight / setting.eyeWidth);
ry = y + (fo.rightEye.Height / setting.featureWidth * setting.eyeHeight / setting.eyeWidth);
}
}
}
//lefteyeloop basically the same type as righteyeloop//
.....
//this to count the distance of righteye and lefteye
double rl = ((rx - lx) * (rx - lx) + (ry - ly) * (ry - ly));
double dRightLeft = Math.Pow(rl, 0.5);
}
I suspect the problem is that Math.Pow deals with doubles, which have low precision (see this SO question for more discussion). The immediate instinct is to just replace Math.Pow by writing out the multiplication:
double rl = ((rx - lx) * (rx - lx) + (ry - ly) * (ry - ly));
double dRightLeft = Math.Sqrt(rl);
From the Math.Pow reference, it seems that, with an exponent of two, the only way to return 0 is if your base (i.e. rx - lx or ry - ly) is also 0.
I have 3 very large signed integers.
long x = long.MaxValue;
long y = long.MaxValue - 1;
long z = long.MaxValue - 2;
I want to calculate their truncated average. Expected average value is long.MaxValue - 1, which is 9223372036854775806.
It is impossible to calculate it as:
long avg = (x + y + z) / 3; // 3074457345618258600
Note: I read all those questions about average of 2 numbers, but I don't see how that technique can be applied to average of 3 numbers.
It would be very easy with the usage of BigInteger, but let's assume I cannot use it.
BigInteger bx = new BigInteger(x);
BigInteger by = new BigInteger(y);
BigInteger bz = new BigInteger(z);
BigInteger bavg = (bx + by + bz) / 3; // 9223372036854775806
If I convert to double, then, of course, I lose precision:
double dx = x;
double dy = y;
double dz = z;
double davg = (dx + dy + dz) / 3; // 9223372036854780000
If I convert to decimal, it works, but also let's assume that I cannot use it.
decimal mx = x;
decimal my = y;
decimal mz = z;
decimal mavg = (mx + my + mz) / 3; // 9223372036854775806
Question: Is there a way to calculate the truncated average of 3 very large integers only with the usage of long type? Don't consider that question as C#-specific, just it is easier for me to provide samples in C#.
This code will work, but isn't that pretty.
It first divides all three values (it floors the values, so you 'lose' the remainder), and then divides the remainder:
long n = x / 3
+ y / 3
+ z / 3
+ ( x % 3
+ y % 3
+ z % 3
) / 3
Note that the above sample does not always work properly when having one or more negative values.
As discussed with Ulugbek, since the number of comments are exploding below, here is the current BEST solution for both positive and negative values.
Thanks to answers and comments of Ulugbek Umirov, James S, KevinZ, Marc van Leeuwen, gnasher729 this is the current solution:
static long CalculateAverage(long x, long y, long z)
{
return (x % 3 + y % 3 + z % 3 + 6) / 3 - 2
+ x / 3 + y / 3 + z / 3;
}
static long CalculateAverage(params long[] arr)
{
int count = arr.Length;
return (arr.Sum(n => n % count) + count * (count - 1)) / count - (count - 1)
+ arr.Sum(n => n / count);
}
NB - Patrick has already given a great answer. Expanding on this you could do a generic version for any number of integers like so:
long x = long.MaxValue;
long y = long.MaxValue - 1;
long z = long.MaxValue - 2;
long[] arr = { x, y, z };
var avg = arr.Select(i => i / arr.Length).Sum()
+ arr.Select(i => i % arr.Length).Sum() / arr.Length;
Patrick Hofman has posted a great solution. But if needed it can still be implemented in several other ways. Using the algorithm here I have another solution. If implemented carefully it may be faster than the multiple divisions in systems with slow hardware divisors. It can be further optimized by using divide by constants technique from hacker's delight
public class int128_t {
private int H;
private long L;
public int128_t(int h, long l)
{
H = h;
L = l;
}
public int128_t add(int128_t a)
{
int128_t s;
s.L = L + a.L;
s.H = H + a.H + (s.L < a.L);
return b;
}
private int128_t rshift2() // right shift 2
{
int128_t r;
r.H = H >> 2;
r.L = (L >> 2) | ((H & 0x03) << 62);
return r;
}
public int128_t divideby3()
{
int128_t sum = {0, 0}, num = new int128_t(H, L);
while (num.H || num.L > 3)
{
int128_t n_sar2 = num.rshift2();
sum = add(n_sar2, sum);
num = add(n_sar2, new int128_t(0, num.L & 3));
}
if (num.H == 0 && num.L == 3)
{
// sum = add(sum, 1);
sum.L++;
if (sum.L == 0) sum.H++;
}
return sum;
}
};
int128_t t = new int128_t(0, x);
t = t.add(new int128_t(0, y));
t = t.add(new int128_t(0, z));
t = t.divideby3();
long average = t.L;
In C/C++ on 64-bit platforms it's much easier with __int128
int64_t average = ((__int128)x + y + z)/3;
You can calculate the mean of numbers based on the differences between the numbers rather than using the sum.
Let's say x is the max, y is the median, z is the min (as you have). We will call them max, median and min.
Conditional checker added as per #UlugbekUmirov's comment:
long tmp = median + ((min - median) / 2); //Average of min 2 values
if (median > 0) tmp = median + ((max - median) / 2); //Average of max 2 values
long mean;
if (min > 0) {
mean = min + ((tmp - min) * (2.0 / 3)); //Average of all 3 values
} else if (median > 0) {
mean = min;
while (mean != tmp) {
mean += 2;
tmp--;
}
} else if (max > 0) {
mean = max;
while (mean != tmp) {
mean--;
tmp += 2;
}
} else {
mean = max + ((tmp - max) * (2.0 / 3));
}
Patching Patrick Hofman's solution with supercat's correction, I give you the following:
static Int64 Avg3 ( Int64 x, Int64 y, Int64 z )
{
UInt64 flag = 1ul << 63;
UInt64 x_ = flag ^ (UInt64) x;
UInt64 y_ = flag ^ (UInt64) y;
UInt64 z_ = flag ^ (UInt64) z;
UInt64 quotient = x_ / 3ul + y_ / 3ul + z_ / 3ul
+ ( x_ % 3ul + y_ % 3ul + z_ % 3ul ) / 3ul;
return (Int64) (quotient ^ flag);
}
And the N element case:
static Int64 AvgN ( params Int64 [ ] args )
{
UInt64 length = (UInt64) args.Length;
UInt64 flag = 1ul << 63;
UInt64 quotient_sum = 0;
UInt64 remainder_sum = 0;
foreach ( Int64 item in args )
{
UInt64 uitem = flag ^ (UInt64) item;
quotient_sum += uitem / length;
remainder_sum += uitem % length;
}
return (Int64) ( flag ^ ( quotient_sum + remainder_sum / length ) );
}
This always gives the floor() of the mean, and eliminates every possible edge case.
Because C uses floored division rather than Euclidian division, it may easier to compute a properly-rounded average of three unsigned values than three signed ones. Simply add 0x8000000000000000UL to each number before taking the unsigned average, subtract it after taking the result, and use an unchecked cast back to Int64 to get a signed average.
To compute the unsigned average, compute the sum of the top 32 bits of the three values. Then compute the sum of the bottom 32 bits of the three values, plus the sum from above, plus one [the plus one is to yield a rounded result]. The average will be 0x55555555 times the first sum, plus one third of the second.
Performance on 32-bit processors might be enhanced by producing three "sum" values each of which is 32 bits long, so that the final result is ((0x55555555UL * sumX)<<32) + 0x55555555UL * sumH + sumL/3; it might possibly be further enhanced by replacing sumL/3 with ((sumL * 0x55555556UL) >> 32), though the latter would depend upon the JIT optimizer [it might know how to replace a division by 3 with a multiply, and its code might actually be more efficient than an explicit multiply operation].
If you know you have N values, can you just divide each value by N and sum them together?
long GetAverage(long* arrayVals, int n)
{
long avg = 0;
long rem = 0;
for(int i=0; i<n; ++i)
{
avg += arrayVals[i] / n;
rem += arrayVals[i] % n;
}
return avg + (rem / n);
}
You could use the fact that you can write each of the numbers as y = ax + b, where x is a constant. Each a would be y / x (the integer part of that division). Each b would be y % x (the rest/modulo of that division). If you choose this constant in an intelligent way, for example by choosing the square root of the maximum number as a constant, you can get the average of x numbers without having problems with overflow.
The average of an arbitrary list of numbers can be found by finding:
( ( sum( all A's ) / length ) * constant ) +
( ( sum( all A's ) % length ) * constant / length) +
( ( sum( all B's ) / length )
where % denotes modulo and / denotes the 'whole' part of division.
The program would look something like:
class Program
{
static void Main()
{
List<long> list = new List<long>();
list.Add( long.MaxValue );
list.Add( long.MaxValue - 1 );
list.Add( long.MaxValue - 2 );
long sumA = 0, sumB = 0;
long res1, res2, res3;
//You should calculate the following dynamically
long constant = 1753413056;
foreach (long num in list)
{
sumA += num / constant;
sumB += num % constant;
}
res1 = (sumA / list.Count) * constant;
res2 = ((sumA % list.Count) * constant) / list.Count;
res3 = sumB / list.Count;
Console.WriteLine( res1 + res2 + res3 );
}
}
I also tried it and come up with a faster solution (although only by a factor about 3/4). It uses a single division
public static long avg(long a, long b, long c) {
final long quarterSum = (a>>2) + (b>>2) + (c>>2);
final long lowSum = (a&3) + (b&3) + (c&3);
final long twelfth = quarterSum / 3;
final long quarterRemainder = quarterSum - 3*twelfth;
final long adjustment = smallDiv3(lowSum + 4*quarterRemainder);
return 4*twelfth + adjustment;
}
where smallDiv3 is division by 3 using multipliation and working only for small arguments
private static long smallDiv3(long n) {
assert -30 <= n && n <= 30;
// Constants found rather experimentally.
return (64/3*n + 10) >> 6;
}
Here is the whole code including a test and a benchmark, the results are not that impressive.
This function computes the result in two divisions. It should generalize nicely to other divisors and word sizes.
It works by computing the double-word addition result, then working out the division.
Int64 average(Int64 a, Int64 b, Int64 c) {
// constants: 0x10000000000000000 div/mod 3
const Int64 hdiv3 = UInt64(-3) / 3 + 1;
const Int64 hmod3 = UInt64(-3) % 3;
// compute the signed double-word addition result in hi:lo
UInt64 lo = a; Int64 hi = a>=0 ? 0 : -1;
lo += b; hi += b>=0 ? lo<b : -(lo>=UInt64(b));
lo += c; hi += c>=0 ? lo<c : -(lo>=UInt64(c));
// divide, do a correction when high/low modulos add up
return hi>=0 ? lo/3 + hi*hdiv3 + (lo%3 + hi*hmod3)/3
: lo/3+1 + hi*hdiv3 + Int64(lo%3-3 + hi*hmod3)/3;
}
Math
(x + y + z) / 3 = x/3 + y/3 + z/3
(a[1] + a[2] + .. + a[k]) / k = a[1]/k + a[2]/k + .. + a[k]/k
Code
long calculateAverage (long a [])
{
double average = 0;
foreach (long x in a)
average += (Convert.ToDouble(x)/Convert.ToDouble(a.Length));
return Convert.ToInt64(Math.Round(average));
}
long calculateAverage_Safe (long a [])
{
double average = 0;
double b = 0;
foreach (long x in a)
{
b = (Convert.ToDouble(x)/Convert.ToDouble(a.Length));
if (b >= (Convert.ToDouble(long.MaxValue)-average))
throw new OverflowException ();
average += b;
}
return Convert.ToInt64(Math.Round(average));
}
Try this:
long n = Array.ConvertAll(new[]{x,y,z},v=>v/3).Sum()
+ (Array.ConvertAll(new[]{x,y,z},v=>v%3).Sum() / 3);
I'm trying to implement the recursive definition for B-Splines in c# but I can't get it right. Here's what I've done:
public static Double RecursiveBSpline(int i, Double[] t, int order, Double x)
{
Double result = 0;
if (order == 0)
{
if (t[i] <= x && x < t[i + 1])
{
result = 1;
}
else
{
result = 0;
}
}
else
{
Double denom1, denom2, num1, num2;
denom1 = t[i + order + 1] - t[i + 1];
denom2 = t[i + order] - t[i];
if (denom1 == 0)
{
num1 = 0;
}
else
{
num1 = t[i + order + 1] - x / denom1;
}
if (denom2 == 0)
{
num2 = 0;
}
else
{
num2 = x - t[i] / denom2;
}
result = num1 * RecursiveBSpline(i + 1, t, order - 1, x)
+ num2 * RecursiveBSpline(i, t, order - 1, x);
}
return result;
}
And here is how I call the function:
Double[] vect = new Double[] { 0, 1, 2, 3 };
MessageBox.Show(BSpline.RecursiveBSpline(0,vect,2,0.5).ToString());
I should see 0,125 on the screen, instead I get 0,25. The two denominator variables are used to check if they equal 0 and if they do, the number should be set to 0 by definition. Can someone point out where I'm getting this wrong?
Bear in mind, that the mathematical and logical operators in C# have a precedence order. Your second solution works fine if you put the right terms in braces (explanation follows). This line:
num2 = x - t[i] / denom2;
should be changed to:
num2 = (x - t[i]) / denom2;
and so on. Then the result is as desired: 0.125
The division operator has a higher order precedence as the addition operator. To affect the execution order use braces (everything in braces will be evaluated at first):
var r1 = 2 + 2 / 2; // Step1: 2 / 2 = 1 Step2: 2 + 1 Output: 3
var r2 = (2 + 2) / 2; // Step1: (2 + 2) = 4 Step2: 4 / 2 = 2 Output: 2
How do I exclude and count values which are bigger than 4095 from this array:
EDIT: so this is the final code I have, it basically works on some mousepoints, however there are some exceptions where the difference between depth and neighbouring values are too big (see green marked box on http://s7.directupload.net/images/131007/uitb86ho.jpg). In the screenshot there is a red box, which contains 441 Pixels, and the average value of those 441 Pixels is 1198 mm, where the depth on x;y 15;463 is only about 614 mm. Have no idea where the bigger average values come from, since it should have been excluded with the if-condition (d < 4095).
protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
{
// Get the x and y coordinates of the mouse pointer.
System.Windows.Point mousePoint = e.GetPosition(imageIR);
double xpos_IR = mousePoint.X;
double ypos_IR = mousePoint.Y;
int x = (int)xpos_IR;
int y = (int)ypos_IR;
lbCoord.Content = "x- & y- Koordinate [pixel]: " + x + " ; " + y;
int d = (ushort)pixelData[x + y * this.depthFrame.Width];
d = d >> 3;
int xpos_Content = (int)((x - 320) * 0.03501 / 2 * d/10);
int ypos_Content = (int)((240 - y) * 0.03501 / 2 * d/10);
xpos.Content = "x- Koordinate [mm]: " + xpos_Content;
ypos.Content = "y- Koordinate [mm]: " + ypos_Content;
zpos.Content = "z- Koordinate [mm]: " + (d);
// Calculate the average value of array element
int sum = 0;
int i;
i = Convert.ToInt32(gr_ordnung.Text);
i = int.Parse(gr_ordnung.Text);
int m;
int n;
int d_mw = 0;
int count = 0;
for (m = x - i; m <= x + i; m++)
{
for (n = y - i; n <= y + i; n++)
{
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
// With condition that if one of those values is more than 4095:
if (d_array <= 4095)
{
sum += d_array;
count++;
d_mw = sum / count;
}
tiefen_mw.Content = "Tiefen-MW [mm]: " + d_mw;
}
}
}
So, the 'if' condition means if I have d_array (in my case 100 Pixels) from m = x-i to m = x+i and n = y-i to n = y+i which is less than 4095 then just do the 'normal' calculation where the average is the sum of all values divided by the number of total elements.
Now the 'else' condition means: if I have d_array value which is more than 4095, then it should be declared as 0 and it doesn't count in the average. Did I write the Syntax correctly?
You could use LinQ to do this quite easily:
using System.Linq;
...
int[] values = new int[10];
// Fill array
...
int[] usefulValues = values.Where(i => i <= 4095).ToArray();
int numberOfUselessValues = values.Length - usefulValues.Length;
UPDATE >>>
Try this instead:
int count_useful = 0; // <<< Important to initialise this here
for (m = x - i; m <= x + i; m++)
{
for (n = y - i; n <= y + i; n++)
{
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
if (d_array <= 4095)
{
sum += d_array;
count_useful++;
}
}
}
d_mw = sum / count_useful; // <<< Perform these sums outside of the loop
tiefen_mw.Content = "Tiefen-MW [mm]: " + d_mw;
Just check before you do anything:
int d_array = (ushort)pixelData[m + n * this.depthFrame.Width];
d_array = d_array >> 3;
if (d_array > 4095) continue; // <-- this
Without knowing more.. its hard to give you a nicer answer.
I am trying to convert a C++ class to C# and in the process learn something of C++. I had never run into a vector<> before and my understanding is this is like a List<> function in C#. During the conversion of the class I re-wrote the code using List futures_price = New List(Convert.ToInt32(no_steps) + 1);. As soon as I run the code, I get a "Index was out of range" error.
Having looked around on SOF, I believe the issue is regarding the parameter being out of index range relating to this, but I do not see a simple solution to solve this with the below code.
In particular, this is the line that is triggering the error: futures_prices[0] = spot_price * Math.Pow(d, no_steps);
Below is the full code:
public double futures_option_price_call_american_binomial(double spot_price, double option_strike, double r, double sigma, double time, double no_steps)
{
//double spot_price, // price futures contract
//double option_strike, // exercise price
//double r, // interest rate
//double sigma, // volatility
//double time, // time to maturity
//int no_steps
List<double> futures_prices = new List<double>(Convert.ToInt32(no_steps) + 1);
//(no_steps+1);
//double call_values = (no_steps+1);
List<double> call_values = new List<double>(Convert.ToInt32(no_steps) + 1);
double t_delta = time/no_steps;
double Rinv = Math.Exp(-r*(t_delta));
double u = Math.Exp(sigma * Math.Sqrt(t_delta));
double d = 1.0/u;
double uu= u*u;
double pUp = (1-d)/(u-d); // note how probability is calculated
double pDown = 1.0 - pUp;
futures_prices[0] = spot_price * Math.Pow(d, no_steps);
int i;
for (i=1; i<=no_steps; ++i) futures_prices[i] = uu*futures_prices[i-1]; // terminal tree nodes
for (i=0; i<=no_steps; ++i) call_values[i] = Math.Max(0.0, (futures_prices[i]-option_strike));
for (int step = Convert.ToInt32(no_steps) - 1; step >= 0; --step)
{
for (i = 0; i <= step; ++i)
{
futures_prices[i] = d * futures_prices[i + 1];
call_values[i] = (pDown * call_values[i] + pUp * call_values[i + 1]) * Rinv;
call_values[i] = Math.Max(call_values[i], futures_prices[i] - option_strike); // check for exercise
};
};
return call_values[0];
}
Here is the original source in C++:
double futures_option_price_call_american_binomial(const double& F, // price futures contract
const double& K, // exercise price
const double& r, // interest rate
const double& sigma, // volatility
const double& time, // time to maturity
const int& no_steps) { // number of steps
vector<double> futures_prices(no_steps+1);
vector<double> call_values (no_steps+1);
double t_delta= time/no_steps;
double Rinv = exp(-r*(t_delta));
double u = exp(sigma*sqrt(t_delta));
double d = 1.0/u;
double uu= u*u;
double pUp = (1-d)/(u-d); // note how probability is calculated
double pDown = 1.0 - pUp;
futures_prices[0] = F*pow(d, no_steps);
int i;
for (i=1; i<=no_steps; ++i) futures_prices[i] = uu*futures_prices[i-1]; // terminal tree nodes
for (i=0; i<=no_steps; ++i) call_values[i] = max(0.0, (futures_prices[i]-K));
for (int step=no_steps-1; step>=0; --step) {
for (i=0; i<=step; ++i) {
futures_prices[i] = d*futures_prices[i+1];
call_values[i] = (pDown*call_values[i]+pUp*call_values[i+1])*Rinv;
call_values[i] = max(call_values[i], futures_prices[i]-K); // check for exercise
};
};
return call_values[0];
};
A List<double> starts out empty until you add items to it. (passing the constructor argument just sets the capacity, preventing costly resizes)
You can't access [0] until you Add() it.
To use it the way you are, use an array instead.
As SLaks says, it's better to use an Array in this situation. C# lists are filled with Add method and values are removed through Remove method... this would be more complicated and memory/performance expensive as you are also replacing values.
public Double FuturesOptionPriceCallAmericanBinomial(Double spotPrice, Double optionStrike, Double r, Double sigma, Double time, Double steps)
{
// Avoid calling Convert multiple times as it can be quite performance expensive.
Int32 stepsInteger = Convert.ToInt32(steps);
Double[] futurePrices = new Double[(stepsInteger + 1)];
Double[] callValues = new Double[(stepsInteger + 1)];
Double tDelta = time / steps;
Double rInv = Math.Exp(-r * (tDelta));
Double u = Math.Exp(sigma * Math.Sqrt(tDelta));
Double d = 1.0 / u;
Double uu = u * u;
Double pUp = (1 - d) / (u - d);
Double pDown = 1.0 - pUp;
futurePrices[0] = spotPrice * Math.Pow(d, steps);
for (Int32 i = 1; i <= steps; ++i)
futurePrices[i] = uu * futurePrices[(i - 1)];
for (Int32 i = 0; i <= steps; ++i)
callValues[i] = Math.Max(0.0, (futurePrices[i] - optionStrike));
for (Int32 step = stepsInteger - 1; step >= 0; --step)
{
for (Int32 i = 0; i <= step; ++i)
{
futurePrices[i] = d * futurePrices[(i + 1)];
callValues[i] = ((pDown * callValues[i]) + (pUp * callValues[i + 1])) * rInv;
callValues[i] = Math.Max(callValues[i], (futurePrices[i] - option_strike));
}
}
return callValues[0];
}