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)
Related
If i run Stata's timer:
timer on 1
(code lines)
timer off 1
timer list 1
I cannot read the result:
timer list 1
1: 325.15 / 2 = 162.5725
The next time the timer produces:
timer list 1
1: 622.47 / 3 = 207.4883
It seems it is dividing 325.15 by 2, dividing 622.47 by 3.
Why? What does pre-division number mean? What does post-division number mean?
I tried reading the manual on the topic and other information online but I couldn't find any answer.
The first number is the time elapsed in seconds and the second is the number of times the timer was turned on and off.
Using the example from the help file:
program tester
version 13
forvalues repeat=1(1)100 {
timer on 1
quietly summarize price
timer off 1
}
timer list 1
return list
end
And the toy dataset auto.dta:
sysuse auto, clear
timer clear 1
tester
1: 0.01 / 100 = 0.0001
scalars:
r(N) = 74
r(sum_w) = 74
r(mean) = 6165.256756756757
r(Var) = 8699525.974268788
r(sd) = 2949.495884768919
r(min) = 3291
r(max) = 15906
r(sum) = 456229
r(t1) = .008
r(nt1) = 100
tester
1: 0.02 / 200 = 0.0001
scalars:
r(N) = 74
r(sum_w) = 74
r(mean) = 6165.256756756757
r(Var) = 8699525.974268788
r(sd) = 2949.495884768919
r(min) = 3291
r(max) = 15906
r(sum) = 456229
r(t1) = .017
r(nt1) = 200
If you clear the timer again:
timer clear 1
tester
1: 0.01 / 100 = 0.0001
scalars:
r(N) = 74
r(sum_w) = 74
r(mean) = 6165.256756756757
r(Var) = 8699525.974268788
r(sd) = 2949.495884768919
r(min) = 3291
r(max) = 15906
r(sum) = 456229
r(t1) = .007
r(nt1) = 100
I have 2 variables where I get 2 times from datePicker and I need to save on a variable the difference between them.
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HHmm"
time2 = timeFormatter.date(from: timeFormatter.string(from: datePicker.date))!
I have tried to get the timeIntervalSince1970 from both of them and them substract them and get the difference on milliseconds which I will turn back to hours and minutes, but I get a very big number which doesn't corresponds to the actual time.
let dateTest = time2.timeIntervalSince1970 - time1.timeIntervalSince1970
Then I have tried using time2.timeIntervalSince(date: time1), but again the result milliseconds are much much more than the actual time.
How I can get the correct time difference between 2 times and have the result as hours and minutes in format "0823" for 8 hours and 23 minutes?
The recommended way to do any date math is Calendar and DateComponents
let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)
The format %02ld adds the padding zero.
If you need a standard format with a colon between hours and minutes DateComponentsFormatter() could be a more convenient way
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)
TimeInterval measures seconds, not milliseconds:
let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30
let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)
let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60
To get duration in seconds between two time intervals, this can be used -
let time1 = Date(timeIntervalSince1970: startTime)
let time2 = Date(timeIntervalSince1970: endTime)
let difference = Calendar.current.dateComponents([.second], from: time1, to: time2)
let duration = difference.second
Now you can do it in swift 5 this way,
func getDateDiff(start: Date, end: Date) -> Int {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([Calendar.Component.second], from: start, to: end)
let seconds = dateComponents.second
return Int(seconds!)
}
I am getting a particular double number from the webservice like 0.097 or 0.034 from the webservice. So if i am getting a particular number like 0.56 or 0.5 i need to add a zero in 0.56 and two zeros in 0.5. How to do this in swift3?
Currently i am doing :
class func appendString(data: Int) -> String {
let value = data
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 3 // for float
formatter.maximumFractionDigits = 3 // for float
formatter.minimumIntegerDigits = 1
formatter.paddingPosition = .afterPrefix
formatter.paddingCharacter = "0"
return formatter.string(from: NSNumber(floatLiteral: Double(value)))!
}
Any idea how to achieve th above told logic?
The issue that you are passing data input in Int type, so it will always ignore fractions
see next example [Swift 3.1]
func formatNumber(_ number: Double) -> String? {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 3 // minimum number of fraction digits on right
formatter.maximumFractionDigits = 3 // maximum number of fraction digits on right, or comment for all available
formatter.minimumIntegerDigits = 1 // minimum number of integer digits on left (necessary so that 0.5 don't return .500)
let formattedNumber = formatter.string(from: NSNumber.init(value: number))
return formattedNumber
}
let formattedNumber = formatNumber(0.5)
print(formattedNumber) // Optional("0.500")
Just few small changes to your code :
func appendString(data: Double) -> String { // changed input type of data
let value = data
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 3 // for float
formatter.maximumFractionDigits = 3 // for float
formatter.minimumIntegerDigits = 1
formatter.paddingPosition = .afterPrefix
formatter.paddingCharacter = "0"
return formatter.string(from: NSNumber(floatLiteral: value))! // here double() is not required as data is already double
}
print(appendString(data: 0.5)) // 0.500
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.
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.