I am trying to translate some Pascal code into C++ code. I am stuck trying to figure out how to translate this portion.
Function ThetaG_JD(jd : double) : double;
var
UT,TU,GMST : double;
begin
**UT := Frac(jd + 0.5);**
jd := jd - UT;
TU := (jd - 2451545.0)/36525;
GMST := 24110.54841 + TU * (8640184.812866 + TU * (0.093104 - TU * 6.2E-6));
**GMST := Modulus(GMST + 86400.0*1.00273790934*UT,86400.0);**
ThetaG_JD := twopi * GMST/86400.0;
end; {Function ThetaG_JD}
I am particularly having trouble with the two lines I made bold. How can I translate this to c++? Thank you so much.
In C++ the equivalent functions would be:
fmod to get a floating point modulus
modf to break a floating point item into its fraction and integral parts (equivalent of Frac).
If you want to calculate Julian Day, Greenwich Mean Sidereal Time and Local Mean Sidereal Time, maybe the below can help you - written in PowerShell:
<#
.Synopsis
Astronomy calculations
.Description
Some helper functions to calculate:
- Julian Day,
- Greenwich Mean Sidereal time,
- Local Mean Sidereal Time.
#>
cls
# https://en.wikipedia.org/wiki/Julian_day#Julian_day_number_calculation
function Get-JulianDay
{
param ( [System.DateTime]$dt )
$year = $dt.Year
$month = $dt.Month
$day = $dt.Day
$hour = $dt.Hour
$minute = $dt.Minute
$second = $dt.Second
$a = [System.Math]::Floor((14 - $month) / 12)
$y = $year + 4800 - $a
$m = $month + 12 * $a - 3
$JDN = $day + [System.Math]::Floor((153 * $m + 2) / 5) + 365 * $y + [System.Math]::Floor($y / 4) - [System.Math]::Floor($y / 100) + [System.Math]::Floor($y / 400) - 32045
$JD = $JDN + ($hour - 12) / 24 + $minute / 1440 + $second / 86400
return ($JD)
}
# https://en.wikipedia.org/wiki/Sidereal_time#Definition
# http://aa.usno.navy.mil/faq/docs/GAST.php
function Get-GMST
{
param ( [double]$JD )
$D = $JD - 2451545.0
$GMST = 18.697374558 + 24.06570982441908 * $D
return ($GMST % 24)
}
function Get-LMST
{
param ( [double]$gmst, [double]$longitude )
return ( $gmst + $longitude / 15.0 )
}
# Test above functions
$current = (Get-Date).ToUniversalTime()
$jd = Get-JulianDay -dt $current
$gmst = Get-GMST -JD $jd
$longitude = 17.668487800
$lmst = Get-LMST -gmst $gmst -longitude $longitude
$lst = [timespan]::FromHours($lmst).ToString()
Write-Host "Local mean sidereal time: $lst"
Related
I'm having issue with using the value of a variable used as input value, in a if statement Here's a piece of my code :
//#version=3
study(title="v5.0", shorttitle="v5.0", overlay=true)
PP_display = input(1, minval=0, maxval=1)
if (PP_display = 1)
xHigh = security(ticker,"D", high[0])
xLow = security(ticker,"D", low[0])
xClose = security(ticker,"D", close[0])
vPP = (xHigh+xLow+xClose) / 3
vR1 = vPP+(vPP-xLow)
vS1 = vPP-(xHigh - vPP)
vR2 = vPP + (xHigh - xLow)
vS2 = vPP - (xHigh - xLow)
vR3 = xHigh + 2 * (vPP - xLow)
vS3 = xLow - 2 * (xHigh - vPP)
plot(vPP, color=change(vPP) ? na : black, title="vPP", style = linebr, linewidth = width, transp=0)
end if
As a result, I'm getting this error : "syntax error at input 'PP_display'".
I can't find why...
Thanks for your help
If you want to compare PP_display variable with an integer you should use == (equal to) operator. Single = is used to declare variables.
There is no end if in pinescript syntax.
You can't use plot function in the local scope, only in global.
Declaring a variable using the security() function in the local scope will produce a compilation error - Can't call 'security' inside: 'if', 'for'
The solution is to move all your calcs, security calls and plot function to the global scope.
If your intention is to hide the plot with the PP_display input you could use a ternary conditional operator ? : directly in the series argument of the plot function.
//#version=3
study(title="v5.0", shorttitle="v5.0", overlay=true)
PP_display = input(1, minval=0, maxval=1)
xHigh = security(ticker,"D", high[0])
xLow = security(ticker,"D", low[0])
xClose = security(ticker,"D", close[0])
vPP = (xHigh+xLow+xClose) / 3
vR1 = vPP+(vPP-xLow)
vS1 = vPP-(xHigh - vPP)
vR2 = vPP + (xHigh - xLow)
vS2 = vPP - (xHigh - xLow)
vR3 = xHigh + 2 * (vPP - xLow)
vS3 = xLow - 2 * (xHigh - vPP)
plot(PP_display == 1 ? vPP : na, color=change(vPP) ? na : black, title="vPP", style = linebr, linewidth = 2, transp=0)
I'm trying to implemenet an assignment problem. I have the following problem when trying to multiply two variables in linear programming (using glpk gusek) in my goal function:
minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z]; #y is a binary variable; Koszty_Suma is total cost for ordez z and car type k
The following error is arising: "model.mod:47: multiplication of linear forms not allowed".
Code (.dat file):
data;
set numery_Zlecen := 1, 2, 3; #order numbers
set Miasta := '*some data: *' #cities.
#order numer (from city to city)
set Zlecenie[1] := Warszawa Paris;
set Zlecenie[2] := Berlin Praha;
set Zlecenie[3] := Praha Amsterdam;
#number of packages for transport for a particular order
param Ilosc_Wyrobow :=
1 10
2 50
3 110;
param Godziny_Pracy := 9; #number of working hours during the day
param Pojemnosc_Samochodu := 35; #capacity of the car (how many packages it can take)
param Srednia_Predkosc := 80; #average car speed
param Spalenie_Paliwa := 0.25; #fuel combustion
param Wynagrodzenie_za_Godzine := 20; #salary for one working hour
param Cena_Noclegu := 100; #price of accommodation
param Dystans: '*some data: *' #km between cities.
param Koszt_Paliwa : '*some data: *' #fuel consumption depends on country.
end;
Code (.mod file):
#INDEXY
#=====================================================================
set Miasta; #i,j
set numery_Zlecen; #z
set Zlecenie{numery_Zlecen} dimen 2; #p,q
set Rodzaj_Transportu; #k
#PARAMETRY
#=====================================================================
param Dystans {Miasta,Miasta};
param Ilosc_Wyrobow{numery_Zlecen};
param Godziny_Pracy >= 0;
param Pojemnosc_Samochodu {Rodzaj_Transportu}>= 0;
param Srednia_Predkosc >=0;
param Spalenie_Paliwa >=0;
param Koszt_Paliwa {Miasta,Miasta};
param Wynagrodzenie_za_Godzine >= 0;
param Cena_Noclegu >= 0;
#ZMIENE
#=====================================================================
var x{Miasta,Miasta,numery_Zlecen} <= 1, >= 0; #variable x equal 1 when we're going the path from city A to city B; otherwise it equals 0
var y{Rodzaj_Transportu,numery_Zlecen} binary <=1, >=0; #variable that shows what types of car/s we are using for order (can be 0 or 1)
var Koszty_Suma{Rodzaj_Transportu,numery_Zlecen}; #total costs
var Koszty_Transportu{numery_Zlecen}; #transport costs
var Koszty_Odpoczynku{numery_Zlecen}; #rest costs
var Koszty_Wynagrodzenia{numery_Zlecen}; #salary costs
#FUNKCjA CELU
#=====================================================================
minimize PATH_COST: sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];
#OGRANICZENIA (constraints)
#=====================================================================
s.t. SOURCE{z in numery_Zlecen, (p,q) in Zlecenie[z], i in Miasta: i = p && p != q}:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 1;
s.t. INTERNAL {z in numery_Zlecen, (p,q) in Zlecenie[z],i in Miasta: i != p && i != q && p != q }:
sum {j in Miasta} (x[i ,j ,z ]) - sum {j in Miasta}( x[j ,i ,z ]) = 0;
s.t. OGR_KM_DZIEN{z in numery_Zlecen,(p,q) in Zlecenie[z], j in Miasta, i in Miasta: i != q}:
if (Dystans[i,j] > (Godziny_Pracy*Srednia_Predkosc)) and i != q then x[i,j,z] = 0;
s.t. OGR_KOSZTY_SUMA{z in numery_Zlecen, k in Rodzaj_Transportu}:
Koszty_Suma[k,z] = (Koszty_Transportu[z] + Koszty_Odpoczynku[z] + Koszty_Wynagrodzenia[z])*ceil(Ilosc_Wyrobow[z]/Pojemnosc_Samochodu[k]);
s.t. OGR_KOSZTY_TRANSPORTU{z in numery_Zlecen}:
Koszty_Transportu[z] = (sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z]*Koszt_Paliwa[i,j] ) ))*Spalenie_Paliwa;
s.t. OGR_KOSZTY_ODPOCZYNKU{z in numery_Zlecen}:
Koszty_Odpoczynku[z] =
(sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Godziny_Pracy*Srednia_Predkosc) * Cena_Noclegu;
s.t. OGR_KOSZTY_WYNAGRODZENIA{z in numery_Zlecen}:
Koszty_Wynagrodzenia[z] =
((sum{i in Miasta} (sum{j in Miasta} ( Dystans[i,j]*x[i,j, z] ) ))/(Srednia_Predkosc)) * Wynagrodzenie_za_Godzine;
s.t. OGR_Y_JEDEN{z in numery_Zlecen}:
sum{k in Rodzaj_Transportu}(y[k,z]) = 1;
solve;
How is it possible to get rid of this error? Any hints how to solve this kind of problem are welcome.
First I think the parentheses are incorrect (note that y[k,z] depends on z). The expression
sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z])*y[k,z];
is not mathematically correct. So, I assume what you meant is:
sum{k in Rodzaj_Transportu}(sum{z in numery_Zlecen}Koszty_Suma[k,z]*y[k,z]);
Let me restate the problem a little bit. I assume we can write this as:
sum((i,j), x[i,j]*y[i,j])
with y a binary variable and x a continuous variable. I also assume 0 <= x[i,j] <= U[i,j]. (U is an upper bound).
Here is a way to linearize this quadratic term. We can introduce a variable z[i,j]=x[i,j]*y[i,j] using the following inequalities:
z[i,j] <= U[i,j]*y[i,j]
z[i,j] <= x[i,j]
z[i,j] >= x[i,j]-U[i,j]*(1-y[i,j])
0 <= z[i,j] <= U[i,j]
Now you just can minimize sum((i,j),z[i,j]). For a similar linearization see link.
ho could I manipulate some Int adding them as minutes and sum them? the result should be in hours and minutes just like 1:15 or 6:30.
My playground gives 1.25 but I expected 1.15
struct standardDayOfWork {
var dailyHours : Double = 0
}
var dayToUse = standardDayOfWork()
enum hourFractions : Double {
case quarter = 15
case half = 30
case threeQuarter = 45
case hour = 60
}
dayToUse.dailyHours += hourFractions.half.rawValue
dayToUse.dailyHours += hourFractions.half.rawValue
dayToUse.dailyHours += hourFractions.quarter.rawValue
var total = dayToUse.dailyHours / 60 //1.25
Because in the decimal system a quarter is 0.25.
To get numeric 1.15 you could use this weird expression:
var total = Double(Int(dayToUse.dailyHours) / 60) + (dayToUse.dailyHours.truncatingRemainder(dividingBy: 60) / 100.0)
Or if you can live with a formatted "hh:mm" string I'd recommend
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.string(from: dayToUse.dailyHours * 60)
We get data from another company in the following formats
374-KH-ON-PEAK|807-KH-OFF-PEAK
82.5-KH-TOTAL|8-K1-CURRENT
44.5-KH-TOTAL
65-KH-ON-PEAK|2.1-K1-ON-PEAK|164-KH-OFF-PEAK|27-K1
These values go into a SQL Server table. The numbers represent electricity usages. I'm working on finding a way to extract the numbers and sum them together.
There is only one condition: the number must be followed by "-KH". If it is followed by "-K1" we don't need to do anything with it.
Upon inputting "65-KH-ON-PEAK|2.1-K1-ON-PEAK|164-KH-OFF-PEAK|27-K1", I need to output 229 which stands for 65 + 164
I'd prefer to find a solution using VBA for Access(For reasons related to the business's current software solutions), but I'm open to other solutions as well.
Using [Excel] can be done like this:
code:
Sub test()
Dim cl As Range, z!, x As Variant, x2 As Variant
For Each cl In [A1:A4]
z = 0
For Each x In Split(cl.Value2, "|")
If x Like "*-KH-*" Then
For Each x2 In Split(x, "-")
If IsNumeric(x2) Then z = z + x2
Next x2
End If
Next x
cl.Offset(, 1).Value = z
Next cl
End Sub
another variant, without second loop (using #shawnt00 comment below OP)
Sub test()
Dim cl As Range, z!, x As Variant
For Each cl In [A1:A4]
z = 0
For Each x In Split(cl.Value2, "|")
If x Like "*-KH-*" Then z = z + Left(x, InStr(1, x, "-") - 1)
Next x
cl.Offset(, 1).Value = z
Next cl
End Sub
output:
Using [Access] can be something like this:
Sub test2()
Dim z!, x As Variant
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Table1")
Do Until rs.EOF = True
z = 0
For Each x In Split(rs!Field1, "|")
If x Like "*-KH-*" Then z = z + Left(x, InStr(1, x, "-") - 1)
Next x
Debug.Print rs!Field1, z
rs.MoveNext
Loop
End Sub
test:
You would do a single bulk insert into an SQL Server table using | as the field terminator, so you would have fields like f1,f2,f3,f4. Then you can use an expression like:
WITH numerics
AS ( SELECT CASE
WHEN PATINDEX('%-KH-%', f1) > 0
THEN CAST(SUBSTRING(f1, 1, PATINDEX('%-KH-%', f1) - 1) AS INT)
ELSE 0
END AS f1,
CASE
WHEN PATINDEX('%-KH-%', f2) > 0
THEN CAST(SUBSTRING(f2, 1, PATINDEX('%-KH-%', f2) - 1) AS INT)
ELSE 0
END AS f2,
CASE
WHEN PATINDEX('%-KH-%', f3) > 0
THEN CAST(SUBSTRING(f3, 1, PATINDEX('%-KH-%', f3) - 1) AS INT)
ELSE 0
END AS f3,
CASE
WHEN PATINDEX('%-KH-%', f4) > 0
THEN CAST(SUBSTRING(f4, 1, PATINDEX('%-KH-%', f4) - 1) AS INT)
ELSE 0
END AS f4
FROM myTable )
SELECT f1 + f2 + f3 + f4 AS rowTotal;
You could do it with a Powershell script, that would give the power of regex to extract and sum the numbers. Something like the example below (I have tested the extracting from the file part but not the Access parts so they may need some tweaking):
$conn = New-Object -ComObject ADODB.Connection
$recordset = New-Object -ComObject ADODB.Recordset
$conn.Open()
$cmd = $conn.CreateCommand()
$ado.open("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=\\path_to\database.accdb")
# Microsoft.Jet.OLEDB.4.0 for older versions of Access
(Select-String file.txt -Pattern '[\d.]+(?=-KH)' -AllMatches) | % {
($_.Matches | % {
[double]$_.Value
} | Measure-Object -Sum).Sum
} | % {
$cmd.CommandText = "INSERT INTO TABLE VALUES($($_))"
Write-Output $cmd.ExecuteNonQuery()
}
$conn.Close()
I would convert Gregorian date to Hijri (Islamic) date. After may search on the web, I found a source code to convert it.
I converted the code from Java and PHP to C base.
The implement some times working without any problem. But some days has problem.
I need your help either fix the implement or a available code that will work without any problem!
BTW I found another source code (http://emr.cs.iit.edu/~reingold/calendar.C) that is C++ base. As I don't know C++ if anyone can convert that to C Base or Objective C would be prefect (still not sure this code will work correctly or not).
P.S. You can check the correct date in: islamicfinder.org/Hcal/index.php
void gregorian_to_hijri(int* h_y, int* h_m, int* h_d, int g_y, int g_m, int g_d)
{
int year, month, day;
int zyr;
int zd;
int zm;
int zy;
float zjd;
int zl;
int zn;
int zj;
year = g_y;
month = g_m;
day = g_d;
zyr = year;
zd = day;
zm = month;
zy = zyr;
if((zy > 1582) || ((zy == 1582) && (zm > 10)) || ((zy == 1582) && (zm == 10) && (zd > 14)))
{
zjd = ((1461 * (zy + 4800 + ((zm - 14) / 12))) / 4)
+ ((367 * (zm - 2 - 12 * (((zm - 14) / 12)))) / 12)
- ((3 * (((zy + 4900 + ((zm - 14) / 12)) / 100))) / 4) + zd - 32075;
}
else
{
zjd = 367 * zy - ((7 * (zy + 5001 + ((zm - 9) / 7))) / 4)
+ ((275 * zm) / 9) + zd + 1729777;
}
zl = zjd - 1948440 + 10632;
zn = ((zl - 1) / 10631);
zl = zl - 10631 * zn + 354;
zj = (((10985 - zl) / 5316)) * ((int)((50 * zl) / 17719))
+ ((zl / 5670)) * ((int)((43 * zl) / 15238));
zl = zl - (((30 - zj) / 15)) * (((17719 * zj) / 50))
- ((zj / 16)) * (((15238 * zj) / 43)) + 29;
zm = ((24 * zl) / 709);
zd = zl - ((709 * zm) / 24);
zy = 30 * zn + zj - 30;
*h_y = zy;
*h_m = zm;
*h_d = zd;
}
Assuming this is for a Mac (Cocoa) or iOS (Cocoa Touch) app, since that's where you see Objective C most often, then you can just do something like this:
// Create a Gregorian Calendar
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Set up components of a Gregorian date
NSDateComponents *gregorianComponents = [[NSDateComponents alloc] init];
gregorianComponents.day = 4;
gregorianComponents.month = 12;
gregorianComponents.year = 2010;
// Create the date
NSDate *date = [gregorianCalendar dateFromComponents:gregorianComponents];
[gregorianComponents release];
[gregorianCalendar release];
// Then create an Islamic calendar
NSCalendar *hijriCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSIslamicCivilCalendar];
// And grab those date components for the same date
NSDateComponents *hijriComponents = [hijriCalendar components:(NSDayCalendarUnit |
NSMonthCalendarUnit |
NSYearCalendarUnit)
fromDate:date];
NSLog(#"[In Hijri calendar ->] Day: %ld, Month: %ld, Year:%ld",
[hijriComponents day],
[hijriComponents month],
[hijriComponents year]);
[hijriCalendar release];
If all you want is the current date, then you can skip setting up the gregorian date altogether and just do this:
// Create an Islamic calendar
NSCalendar *hijriCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSIslamicCalendar];
// And grab the date components for the current date
NSDateComponents *hijriComponents = [hijriCalendar components:(NSDayCalendarUnit |
NSMonthCalendarUnit |
NSYearCalendarUnit)
fromDate:[NSDate date]];
[hijriCalendar release];
Have a look at this topic: how to convert hijari date into gregorian date in java script?
The question mentions JavaScript but the top answer seems to have links to implementations in a variety of languages.
You should be able to do this in Objective-C (if that really is an option) using NSCalendar.