I am attempting to convert the first code snippet at:
Calculate distance between 2 GPS coordinates
// var R = 6371; // km
// var dLat = (lat2-lat1).toRad();
// var dLon = (lon2-lon1).toRad();
// var lat1 = lat1.toRad();
// var lat2 = lat2.toRad();
// var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
// Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
// var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
// var d = R * c;
(also shown below) for use in qt c++. It is used in a program that simulates gps flight inside of a radio control simulator. The GpsCalcLoop grabs gps latitude and longitude (in decimal format) once per second. These are fed into my converted code in hopes of getting a distance traveled during that one second of time. Speed would then be calculated.
I used the information at this page:
http://doc.qt.io/qt-4.8/qtcore-qmath-h.html
to convert the math functions. The output, however, is not what I expected. No matter what is input into lat2, lat1, lon2, and lon1 the results are always the same, '16777200.00'.
I am hoping that someone more familiar with qt c++ will be able to show me where I have gone wrong with the conversion. or point me to where I can find qt c++ code that is working.
I will add that I have attempted to use "#include "<"QGeoPositionInfo">" but get a 'No such file or directory' error when running the program.
void TelemetrySimulator::onGpsCalcLoop()
{
if(rungps)
{
ui -> valuetest1 -> setValue(flat);
ui -> valuetest2 -> setValue(flat2);
ui -> valuetest3 -> setValue(flon);
ui -> valuetest4 -> setValue(flon2);
ui -> valuetest5 -> setValue(flat-flat2);
ui -> valuetest6 -> setValue(flon-flon2);
flat2 = flat;
flon2 = flon;
//--https://stackoverflow.com/questions/365826 //calculate-distance-between-2-gps-coordinates--
// var R = 6371; // km
// var dLat = (lat2-lat1).toRad();
// var dLon = (lon2-lon1).toRad();
// var lat1 = lat1.toRad();
// var lat2 = lat2.toRad();
// var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
// Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
// var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
// var d = R * c;
//--------------my conversio to qt c++---------
//---converted to qt using this web page -> http://doc.qt.io/qt-4.8/qtcore-qmath-h.html----
double R, dLat, dLon, lat1, lat2, lon2, lon1, a, c, d;
lat2 = flat2;
lat1 = flat;
lon2 = flon2;
lon1 = flon;
R = 6371; // km
dLat = qAcos(lat2-lat1); //dLat = (lat2-lat1).toRad(); instead of qAcos could be qAsin, qAtan, qCos, qSin,
// qTan. All refer to Radials.
dLon = qAcos(lon2-lon1); //dLon = (lon2-lon1).toRad();
lat1 = qAcos(lat1); //lat1 = lat1.toRad();
lat2 = qAcos(lat2); //lat2 = lat2.toRad();
a = qSin(dLat/2) * qSin(dLat/2) + //Math.sin(dLat/2) * Math.sin(dLat/2) +
qSin(dLon/2) * qSin(dLon/2) * qCos(lat1) * qCos(lat2);//Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
c = 2 * qAtan2(qSqrt(a), qSqrt(1-a)); //Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = R * c;
ui -> valuetest7 -> setValue(d);
}
}
Thanks to everyone for your great help! Here is the final code:
void MainWindow::onGpsCalcLoop()
{
//Get initial values from gps run loop-------
double lat2 = flat2;
double lat1 = flat;
double lon2 = flon2;
double lon1 = flon;
//GPS distance and speed calculation -------
double dLat = .01745329 * (lat2 - lat1);
double dLon = .01745329 * (lon2 - lon1);
lat1 = .01745329 * lat1;
lat2 = .01745329 * lat2;
double a = qSin(dLat/2) * qSin(dLat/2) +
qSin(dLon/2) * qSin(dLon/2) * qCos(lat1) * qCos(lat2);
double c = 2 * qAtan2(qSqrt(a), qSqrt(1-a));
double d = 3975 * c;
//Distance calculation done. Next is total distance and speed------
td = td + d;
if (d > .1)
{
d = 0;
td = 0;
}
if (ui -> metric -> isChecked())
{
ui -> valuetest1 -> setValue(td * 1.6);
ui -> valuetest2 -> setValue((d * 3600) * 1.6);
}
else
{
ui -> valuetest1 -> setValue(td);
ui -> valuetest2 -> setValue(d * 3600);
}
flat2 = flat;
flon2 = flon;
}
I used .01745329*(whatever) instead of qDegreesToRadians(whatever) just to keep things as simple as possible.
Again, thanks to all for your help!
Related
I'm trying out the PROC CALIS LINEQS example outlined here (it works when I use the PATH and RAM examples) using the Wheaton dataset (I've renamed the headers to match the code below) with this code:
proc calis nobs=932 data=Wheaton;
lineqs
Anomie67 = 1.0 * f_Alien67 + E1,
Powerless67 = 0.833 * f_Alien67 + E2,
Anomie71 = 1.0 * f_Alien71 + E3,
Powerless71 = 0.833 * f_Alien71 + E4,
Education = 1.0 * f_SES + E5,
SEI = lambda * f_SES + E6,
f_Alien67 = gamma1 * f_SES + D1,
f_Alien71 = gamma2 * f_SES + beta * Alien67 + D2;
std
E1 = theta1,
E2 = theta2,
E3 = theta1,
E4 = theta2,
E5 = theta3,
E6 = theta4,
D1 = psi1,
D2 = psi2,
f_SES = phi;
cov
E1 E3 = theta5,
E2 E4 = theta5;
run;
but I get this error:
"Predictor variable Alien67 in the equation with outcome variable f_Alien71 is neither a manifest, an F, an E, nor a D variable."
What am I doing wrong?
okay, I found the error - I had to consult page 450 of the SAS OnlineDoc™: Version 8 to find the solution which is basically to change this line of code:
f_Alien71 = gamma2 * f_SES + beta * Alien67 + D2;
to
f_Alien71 = gamma2 * f_SES + beta * f_Alien67 + D2;
I got a clue when I was reading page 450 because V5 in the book which corresponds to SEI in the code was using F3 (which was f_SES) as an input and then I noticed that the input to F2 in the book (which was f_Alien71 in the code) was F1 (which was f_Alien67 in the code) and I found that there was a mismatch.
I have an R function to compute the probability of the integer k; k = 1, ....., m from the given values of the other parameters. When the size of the k is very large (e.g., m = 10,000), the function is very slow. Do you have any suggestions to improve the performance of the function?
I also want to create an equivalent function in C++ if needed so that I can use RCPP package from R, but I do not know C++. Before learning C++ from the scratch, I also would like to have your suggestions.
prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
m = m0 + m1
t <- rnorm(nrep, et, 1)
p0 <- pnorm(-t)
p1 <- pnorm(ey - t)
mean0 <- (m0 - 1)*p0 + m1*p1 + 1
mean1 <- m0*p0 + (m1 - 1)*p1 + 1
var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)
prob <- ifelse(et == 0, mean(dnorm(k, mean0, sqrt(var0))),
mean(dnorm(k, mean1, sqrt(var1))))
return(prob)
}
apply the function
prob_k <- sapply(1:10000, prob, et=1, ey=1 ,m0 = 5000, m1 = 5000)
Since dnorm is a vectorized function, you can just call prob like
prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000)
To get verctorized outputs, you will have to change the code of the function a bit though
prob <- function(k, et, ey, nrep = 10000, m0, m1)
{
m = m0 + m1
t <- rnorm(nrep, et, 1)
p0 <- pnorm(-t)
p1 <- pnorm(ey - t)
mean0 <- (m0 - 1)*p0 + m1*p1 + 1
mean1 <- m0*p0 + (m1 - 1)*p1 + 1
var0 <- (m0 - 1)*p0*(1 - p0) + m1*p1*(1 - p1)
var1 <- m0*p0*(1 - p0) + (m1 - 1)*p1*(1 - p1)
if( et == 0 )
dnorm(k, mean0, sqrt(var0))
else
dnorm(k, mean1, sqrt(var1))
}
This is pretty fast on my machine (5 milliseconds on average)
microbenchmark(prob_k <- prob(1:10000, et = 1, ey = 1 ,m0 = 5000, m1 = 5000))
# Unit: milliseconds
# expr min
# prob_k <- prob(1:10000, et = 1, ey = 1, m0 = 5000, m1 = 5000) 4.68232
# lq mean median uq max neval
# 4.776912 5.168405 4.817979 4.907612 7.023989 100
I am trying to implement an rk4 function to solve 2 differential equations. I have this code that implements the Runge Kutta 4 method:
//RK4 method
func rk4_func(y_array: [Double], f_array: [(([Double], Double) -> Double)], t_val: Double, h_val: Double) -> [Double] {
let length = y_array.count
let t_half_step = t_val + h_val / 2.0
let t_step = t_val + h_val
var k1 = [Double](repeating: 0.0, count: length)
var k2 = [Double](repeating: 0.0, count: length)
var k3 = [Double](repeating: 0.0, count: length)
var k4 = [Double](repeating: 0.0, count: length)
var w = [Double](repeating: 0.0, count: length)
var result = [Double](repeating: 0.0, count: length)
for i in 0...length {
k1[i] = h_val * f_array[i](y_array, t_val)
w[i] = y_array[i] + k1[i]/2.0
}
for i in 0...length {
k2[i] = h_val * f_array[i](w, t_half_step)
w[i] = y_array[i] + k2[i]/2.0
}
for i in 0...length {
k3[i] = h_val * f_array[i](w, t_half_step)
w[i] = y_array[i] + k3[i]
}
for i in 0...length {
k4[i] = h_val * f_array[i](w, t_step)
}
for i in 0...length {
result[i] = y_array[i] + (k1[i] + 2.0*k2[i] + 2.0*k3[i] + k4[i])/6.0
}
print(result)
return result;
}
But now I need to actually use it, which is the part I'm confused about. If anyone has experience with numerically computing solutions to differential equations, that would help.
What arrays do I need to feed this function?
What does the t_val argument represent? Is it a maximum time?
How does the output "solve" the equation?
What does the output give me?
In the line k1[i] = h_val * f_array[i](y_array, t_val), what does f_array[i](y_array, t_val) mean? Is it saying that for the i-th value of f_array, find the corresponding i-th value for y_array? Then what does the t_val mean there?
For reference, here are the 2 differential equations needed to be solved. The context is that I'm trying to numerically solve these Lotka-Volterra Models to plot a time series and a phase space plot in Xcode (Swift 3.x).
y is the vector of the current state (implemented as double array). f_array is a function pointer to a function doty = f_array(y,t).
t_val is the time for the current state, h_val is the time step.
One call of rk4_func performs the time step from t_val to t_val+h_val and
returns the new state, y_next = rk4_func(y, f_array, t, h).
One would have to study the language internals. Hopefully, that is, for the code to work correctly, the first call of f_array[0](y_array, t_val) computes the full vector/array-valued result and further calls just extract the components of the cached result.
The original code as found at https://github.com/pdemarest/swift-rk4 is severely deficient in its RK4 realization and out-of-date in language standards. A working version as tested at https://swift.sandbox.bluemix.net/ is
import Foundation
func RK4step(y: [Double], f: ([Double], Double) -> [Double], t: Double, h: Double) -> [Double] {
let length = y.count
var w = [Double](repeating: 0.0, count: length )
var result = [Double](repeating: 0.0, count: length)
let k1 = f(y,t)
assert(k1.count == y.count, "States and Derivatives must be the same length")
for i in 0..<length { w[i] = y[i] + 0.5*h*k1[i] }
let k2 = f(w, t+0.5*h)
for i in 0..<length { w[i] = y[i] + 0.5*h*k2[i] }
let k3 = f(w,t+0.5*h)
for i in 0..<length { w[i] = y[i] + h*k3[i]
}
let k4 = f(w,t+h)
for i in 0..<length {
result[i] = y[i] + (k1[i] + 2.0*k2[i] + 2.0*k3[i] + k4[i])*h/6.0
}
return result;
}
func test_exp(){
// Integrate: y' = y
// y_0 = 1.0
// from 0 to 2.0
var y = [1.0]
func deriv (y: [Double], t: Double) -> [Double] {
return [ y[0] ]
}
var t = 0.0
let h = 0.1
while t < 2.0 {
y = RK4step(y:y, f:deriv, t:t, h:h)
t += h
print("t: \(t), y: \(y[0]) exact: \(exp(t))\n")
}
let exact = exp(2.0)
let error = abs(y[0] - exact)
assert(error < pow(h, 4.0))
print("y: \(y[0]) exact: \(exact) error: \(error)\n")
}
print("testing...\n")
test_exp()
For the Volterra-Lotka dynamics one would have to change
var y = [150.0, 5.0]
let a = 5.0
let b = 1.0
let eps = 0.1
let m = 5.0
func deriv (y: [Double], t: Double) -> [Double] {
let p = y[0]
let q = y[1]
return [ a*p-b*p*q, eps*b*p*q - m*q ]
}
with properly fixed global constants a,b,eps,m and a two-dimensional initial value. Add print statements where required.
Am converting some C++ code to VB.NET and need to convert assignments within expressions. Below are some C++ lines of code for which it's not clear what the converted results would be:
i2 = 1 + (i1 = i + i)
i4 = 1 + (i3 = n - i1)
wr = (wtemp = wr) * wpr - wi * wpi + wr
data(0) = (h1r = data(0)) + data(1)
data(0) = c1 * ((h1r = data(0)) + data(1))
Would the first line translate to:
If i2 = 1 Then i1 = i + i
?
Hans gave you the procedure - but just in case there's still any doubt about how to do this, your final result should be:
i1 = i + i
i2 = 1 + i1
i3 = n - i1
i4 = 1 + i3
wtemp = wr
wr = wtemp * wpr - wi * wpi + wr
h1r = data(0)
data(0) = h1r + data(1)
h1r = data(0)
data(0) = c1 * (h1r + data(1))
The code is already converted to VB.NET!
For example if you look at the following VB.NET code
Dim i2 As Int16
Dim i1 As Int16
Dim i As Int16
Dim data(0 To 1)
i = 1
i1 = 1
i2 = 0
i2 = 1 + (i1 = i + i) 'Same as your C++ code
MsgBox(i2)
It will return 1. The code translates to
i2 = 1 + (if i1= i+i)
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.