Ahmed Faizan - 1 year ago 84
C# Question

# Timespan Arithematics to predict tide

I am trying to predict tide in c# using a formula given below:

The program was already done in excel, however when translating it to c# I am encountering some problems.

This is the formula in excel:

`=PI()*((C18)/(C19)+1)`

Cells C18 and C19 just contain subtraction of two date cells each

In C# I am having trouble finding A.

There are 2 problematic areas in finding A.

Problem1: When I do
`(t - t1)/(t2 - t1)`
the answer in C# is 0, but in excel the answer is 1.

Problem 2: the +1 at the end of equation. How do you add a number to timeSpan(in excel this works, maybe because they parse it as a datetime value?)

Here is my code:

``````DateTime t = new DateTime(2016, 6, 21, 13, 41, 00);
DateTime t1 = new DateTime(2016, 6, 21, 7, 13, 00);
DateTime t2 = new DateTime(2016, 6, 21, 13, 57, 00);
double h1 = 1.421;
double h2 = 2.337;
double h2_minus_h1 = h2 - h1;
TimeSpan t_minus_t1 = TimeSpan.FromTicks(t.Subtract(t1).Ticks);
TimeSpan t2_minus_t1 = TimeSpan.FromTicks(t2.Subtract(t1).Ticks);
TimeSpan MainCalculationForA = TimeSpan.FromTicks((t.Subtract(t1).Ticks) / (t2.Subtract(t1).Ticks));
MessageBox.Show(MainCalculationForA.ToString());
``````

The answer for this which is
`(t - t1)/(t2 - t1)`
is:
`00:00:00`
, while in excel it is just 1

Note:The formula is taken from here
tide prediction pdf

note:
`(t - t1)`
and
`(t2 - t1)`
both have exactly the same answer in both C# and excel. So why the difference in answer upon division?

From the PDF provided, `t`, `t1` and `t2` are in decimal hours, so you need `.TotalHours` instead

``````DateTime t = new DateTime(2016, 6, 21, 13, 41, 00);
DateTime t1 = new DateTime(2016, 6, 21, 7, 13, 00);
DateTime t2 = new DateTime(2016, 6, 21, 13, 57, 00);
double h1 = 1.421;
double h2 = 2.337;

double t_min_t1 = (t - t1).TotalHours;
double t2_min_t1 = (t2 - t1).TotalHours;

double A = Math.PI*(t_min_t1/t2_min_t1 + 1);
double h = h1 + (h2 - h1)*((Math.Cos(A) + 1)/2);

MessageBox.Show(h.ToString());
``````

The end result is `2.33345960154238`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download