Swift Compile Perfomance is too slowly for a simple source code - swift

I trying to make a little Swift 3 code to convert Sonar Date to Lunar Date.
A very tiny code, but Xcode take around 10 minutes to compile that.
Could you please give me some advice to improve performance.
Here are my swift code:
class DateExtensions {
let PI: Double = M_PI
func jdFromDate(day: Int, month: Int, year: Int) ->Int {
let a: Int = (14 - month) / 12
let y: Int = year + 4800 - a
let m: Int = month + 12 * a - 3
var jd: Int = day + (153 * m + 2)/5 + 365 * y + y/4 - y/100 + y/400 - 32045
if (jd < 2299161) {
jd = day + (153 * m + 2)/5 + 365 * y + y/4 - 32083
}
return jd
}
func jdToDate(_ jd: Int) -> [Int] {
var a: Int = 0
var b: Int = 0
var c: Int = 0
if (jd > 2299160) { // After 5/10/1582, Gregorian calendar
a = jd + 32044
b = (4 * a + 3) / 146097
c = a - (b * 146097) / 4
} else {
b = 0
c = jd + 32082
}
let d: Int = (4 * c + 3)/1461
let e: Int = c - (1461 * d)/4
let m: Int = (5 * e + 2)/153
let day: Int = e - (153 * m + 2)/5 + 1
let month: Int = m + 3 - 12 * (m/10)
let year: Int = b * 100 + d - 4800 + m/10
return [day, month, year]
}
func SunLongitude(_ jdn: Double) -> Double {
return SunLongitudeAA98(jdn)
}
func SunLongitudeAA98(_ jdn: Double) -> Double {
let T: Double = (jdn - 2451545.0 ) / 36525 // Time in Julian centuries from 2000-01-01 12:00:00 GMT
let T2: Double = T * T
let dr: Double = PI/180 // degree to radian
let M: Double = 357.52910 + 35999.05030 * T - 0.0001559 * T2 - 0.00000048 * T * T2 // mean anomaly, degree
let L0: Double = 280.46645 + 36000.76983 * T + 0.0003032 * T2 // mean longitude, degree
var DL: Double = (1.914600 - 0.004817 * T - 0.000014 * T2) * sin(dr * M)
DL = DL + (0.019993 - 0.000101 * T) * sin(dr * 2 * M) + 0.000290 * sin(dr * 3 * M)
var L: Double = L0 + DL // true longitude, degree
L = Double(L - 360 * (INT(L/360))) // Normalize to (0, 360)
return L
}
func NewMoon(_ k: Int) -> Double {
return NewMoonAA98(k)
}
func NewMoonAA98(_ k: Int) -> Double {
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
var T2: Double = T * T
var T3: Double = T2 * T
var dr: Double = PI/180
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
Jd1 = Jd1 + 0.00033*sin((166.56 + 132.87*T - 0.009173*T2)*dr) // Mean new moon
var M: Double = Double(359.2242 + 29.10535608*k - 0.0000333*T2 - 0.00000347*T3) // Sun's mean anomaly
var Mpr: Double = Double(306.0253 + 385.81691806*k + 0.0107306*T2 + 0.00001236*T3) // Moon's mean anomaly
var F: Double = Double(21.2964 + 390.67050646*k - 0.0016528*T2 - 0.00000239*T3) // Moon's argument of latitude
var C1: Double = (0.1734 - 0.000393*T)*sin(M*dr) + 0.0021*sin(2*dr*M)
C1 = C1 - 0.4068*sin(Mpr*dr) + 0.0161*sin(dr*2*Mpr)
C1 = C1 - 0.0004*sin(dr*3*Mpr)
C1 = C1 + 0.0104*sin(dr*2*F) - 0.0051*sin(dr*(M+Mpr))
C1 = C1 - 0.0074*sin(dr*(M-Mpr)) + 0.0004*sin(dr*(2*F+M))
C1 = C1 - 0.0004*sin(dr*(2*F-M)) - 0.0006*sin(dr*(2*F+Mpr))
C1 = C1 + 0.0010*sin(dr*(2*F-Mpr)) + 0.0005*sin(dr*(2*Mpr+M))
var deltat: Double = 0
if (T < -11) {
deltat = 0.001 + 0.000839 * T + 0.0002261 * T2 - 0.00000845 * T3 - 0.000000081 * T * T3
} else {
deltat = -0.000278 + 0.000265 * T + 0.000262 * T2
}
let JdNew: Double = Jd1 + C1 - deltat
return JdNew
}
func INT(_ d: Double) -> Int {
return Int(exactly: floor(d))!
}
func getSunLongitude(_ dayNumber: Int, _ timeZone: Double) -> Double {
return SunLongitude(dayNumber - 0.5 - timeZone/24)
}
func getNewMoonDay(_ k: Int, _ timeZone: Double) -> Int {
let jd: Double = NewMoon(k)
return INT(jd + 0.5 + timeZone/24)
}
func getLunarMonth11(_ yy: Int, _ timeZone: Double) -> Int {
var off: Double = jdFromDate(31, 12, yy) - 2415021.076998695
var k: Int = INT(off / 29.530588853)
var nm: Int = getNewMoonDay(k, timeZone)
var sunLong: Int = INT(getSunLongitude(nm, timeZone)/30)
if (sunLong >= 9) {
nm = getNewMoonDay(k-1, timeZone)
}
return nm
}
func getLeapMonthOffset(_ a11: Int, _ timeZone: Double) -> Int {
var k: Int = INT(0.5 + (a11 - 2415021.076998695) / 29.530588853)
var last: Int = 0 // Month 11 contains point of sun longutide 3*PI/2 (December solstice)
var i: Int = 1 // We start with the month following lunar month 11
var arc = INT(getSunLongitude(getNewMoonDay(k+i, timeZone), timeZone)/30)
repeat {
last = arc
i = i + 1
arc = INT(getSunLongitude(getNewMoonDay(k+i, timeZone), timeZone)/30)
} while (arc != last && i < 14)
return i - 1
}
func convertSolar2Lunar(_ dd: Int, _ mm: Int, _ yy: Int, _ timeZone: Double) -> [Int] {
var lunarDay: Int = 0
var lunarMonth: Int = 0
var lunarYear: Int = 0
var lunarLeap: Int = 0
var dayNumber: Int = jdFromDate(dd, mm, yy)
var k: Int = INT((dayNumber - 2415021.076998695) / 29.530588853)
var monthStart: Int = getNewMoonDay(k + 1, timeZone)
if (monthStart > dayNumber) {
monthStart = getNewMoonDay(k, timeZone)
}
var a11: Int = getLunarMonth11(yy, timeZone)
var b11: Int = a11
if (a11 >= monthStart) {
lunarYear = yy
a11 = getLunarMonth11(yy-1, timeZone)
} else {
lunarYear = yy + 1
b11 = getLunarMonth11(yy + 1, timeZone)
}
lunarDay = dayNumber - monthStart + 1
var diff: Int = INT((monthStart - a11)/29)
lunarLeap = 0
lunarMonth = diff + 11
if (b11 - a11 > 365) {
var leapMonthDiff: Int = getLeapMonthOffset(a11, timeZone)
if (diff >= leapMonthDiff) {
lunarMonth = diff + 10
if (diff == leapMonthDiff) {
lunarLeap = 1
}
}
}
if (lunarMonth > 12) {
lunarMonth = lunarMonth - 12
}
if (lunarMonth >= 11 && diff < 4) {
lunarYear = lunarYear - 1
}
return [lunarDay, lunarMonth, lunarYear, lunarLeap]
}
func convertLunar2Solar(_ lunarDay: Int, _ lunarMonth: Int, _ lunarYear: Int, _ lunarLeap: Int, _ timeZone: Double) -> [Int]{
var a11: Int = 0
var b11: Int = 0
if (lunarMonth < 11) {
a11 = getLunarMonth11(lunarYear-1, timeZone)
b11 = getLunarMonth11(lunarYear, timeZone)
} else {
a11 = getLunarMonth11(lunarYear, timeZone)
b11 = getLunarMonth11(lunarYear+1, timeZone)
}
var k: Int = INT(0.5 + (a11 - 2415021.076998695) / 29.530588853)
var off: Int = lunarMonth - 11
if (off < 0) {
off = off + 12
}
if (b11 - a11 > 365) {
var leapOff: Int = getLeapMonthOffset(a11, timeZone)
var leapMonth: Int = leapOff - 2
if (leapMonth < 0) {
leapMonth = leapMonth + 12
}
if (lunarLeap != 0 && lunarMonth != leapMonth) {
//debugPrint("Invalid input!")
return new [0, 0, 0]
} else if (lunarLeap != 0 || off >= leapOff) {
off = off + 1
}
}
let monthStart: Int = getNewMoonDay(k + off, timeZone)
return jdToDate(monthStart+lunarDay-1)
}
}
update 1:
//
// DateExtensions.swift
// Sonar2Lunar
//
// Created by Nguyen Thanh Hai on 5/7/17.
// Copyright © 2017 Nguyen Thanh Hai. All rights reserved.
//
import Foundation
import SwiftDate
class DateExtensions {
let PI: Double = M_PI
func jdFromDate(_ day: Int, _ month: Int, _ year: Int) ->Int {
let a: Int = (14 - month) / 12
let y: Int = year + 4800 - a
let m: Int = month + 12 * a - 3
var jd: Int = day + (153 * m + 2)/5 + 365 * y + y/4 - y/100 + y/400 - 32045
if (jd < 2299161) {
jd = day + (153 * m + 2)/5 + 365 * y + y/4 - 32083
}
return jd
}
func jdToDate(_ jd: Int) -> [Int] {
var a: Int = 0
var b: Int = 0
var c: Int = 0
if (jd > 2299160) { // After 5/10/1582, Gregorian calendar
a = jd + 32044
b = (4 * a + 3) / 146097
c = a - (b * 146097) / 4
} else {
b = 0
c = jd + 32082
}
let d: Int = (4 * c + 3)/1461
let e: Int = c - (1461 * d)/4
let m: Int = (5 * e + 2)/153
let day: Int = e - (153 * m + 2)/5 + 1
let month: Int = m + 3 - 12 * (m/10)
let year: Int = b * 100 + d - 4800 + m/10
return [day, month, year]
}
func INT(_ d: Double) -> Int {
return Int(exactly: floor(d))!
}
func SunLongitude(_ jdn: Double) -> Double {
return SunLongitudeAA98(jdn)
}
func SunLongitudeAA98(_ jdn: Double) -> Double {
let T: Double = (jdn - 2451545.0 ) / 36525 // Time in Julian centuries from 2000-01-01 12:00:00 GMT
let T2: Double = T * T
let dr: Double = PI/180 // degree to radian
let M: Double = 357.52910 + 35999.05030 * T - 0.0001559 * T2 - 0.00000048 * T * T2 // mean anomaly, degree
let L0: Double = 280.46645 + 36000.76983 * T + 0.0003032 * T2 // mean longitude, degree
var DL: Double = (1.914600 - 0.004817 * T - 0.000014 * T2) * sin(dr * M)
DL = DL + (0.019993 - 0.000101 * T) * sin(dr * 2 * M) + 0.000290 * sin(dr * 3 * M)
var L: Double = L0 + DL // true longitude, degree
L = L - Double(360 * (INT(L/360))) // Normalize to (0, 360)
return L
}
}

The problem is partly that you know nothing of Swift numerics, and partly that Swift is not very good at handling large amounts of bad numeric code. A particularly egregious spot is:
func NewMoonAA98(_ k: Int) -> Double {
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
var T2: Double = T * T
var T3: Double = T2 * T
var dr: Double = PI/180
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
Those lines alone are enough to send both the parser and the compiler in to a complete tailspin. You cannot combine an Int and a Double in the same expression. So this line:
var T: Double = k/1236.85 // Time in Julian centuries from 1900 January 0.5
needs to be
var T: Double = Double(k)/1236.85 // Time in Julian centuries from 1900 January 0.5
and this line:
var Jd1: Double = Double(2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3)
needs to be
var Jd1: Double = Double(2415020.75933 + 29.53058868*Double(k) + 0.0001178*T2 - 0.000000155*T3)
Those kinds of mistakes permeate your code, and the result is that the compiler is basically spinning its wheels; your code is such a numeric mess that the compiler doesn't know where to start to pinpoint the errors, they are so numerous and so mutually dependent. You could submit your code to Apple as a bug report, but really you could make more of an effort to be kind to the compiler.

Related

Interest Rate Function

I found some code online regarding a finance calculator function but I'm not sure what it does, I'm still new to swift so if someone could explain the purpose of the function I would appreciate it a lot
func calculateAnnualInterestRate() -> Double {
let numberOfMonths = Double(self.NumberofPayments)
var x = 1 + (((self.MonthlyPayment * numberOfMonths/self.loan) - 1) / 12)
func F(_ x: Double) -> Double {
let F = self.loan * x * pow(1 + x, numberOfMonths) / (pow(1 + x, numberOfMonths) - 1) - self.MonthlyPayment
return F;
}
func F_Prime(_ x: Double) -> Double {
let F_Prime = self.loan * pow(x + 1, numberOfMonths - 1) * (x * pow(x + 1, numberOfMonths) + pow(x + 1, numberOfMonths) - (numberOfMonths * x) - x - 1) / pow(pow(x + 1, numberOfMonths) - 1, 2)
return F_Prime
}
while(abs(F(x)) > Double(0.000001)) {
x = x - F(x) / F_Prime(x)
}
let I = Double(12 * x * 100)
if I < 0 || I.isNaN || I.isInfinite {
self.interest = 0.0;
return self.interest
} else {
self.interest = I.roundTo2()
return self.interest
}
}
I know that the function is necessary for the calculation of interest rate but I'm not sure what the F and F_Prime

Running different objects in IDEA - Scala

I have 3 different objects that I've written in IDEA, labelled PartA, PartB, and PartC. However, when I attempt to run any of these objects, the only one that gives me the option to run is PartB. When I right click on the code for PartA and PartC, I have no option to run them. Only PartB has the option to run. What's going on here, and how can I fix it so I can run the different objects I have written?
Edit: Sorry, first time posting a question here. Here's the code I have written.
object PartB extends App {
def easter(Y:Int): Int = {
val N = Y - 1900
val A = N - (N/19) * 19
val B = (7 * A + 1) / 19
val C = 11 * A + 4 - B
val M = C - (C / 29) * 29
val Q = N / 4
val S = N + Q + 31 - M
val W = S - (S / 7) * 7
val DATE = 25 - M - W
return DATE
}
println("Enter a year: ")
val year = scala.io.StdIn.readInt()
val date = easter(year)
var easter_day : String = ""
if (date == 0) {
easter_day = "March, 31"
} else if (date < 0) {
easter_day = "March, " + (31 + year)
} else {
easter_day = "April, " + date
}
println("In " + year + ", Easter is on " + easter_day + ".")
}
////////////////////////////////////////////////////////////////////////////////
object PartC {
def ack(m:Int, n:Int) : Int = {
if (m == 0) {
return n + 1
} else if (n == 0) {
return ack(m - 1, 1)
} else {
return ack(m - 1, ack(m, n - 1))
}
}
println("Enter a value for m: ")
val m = scala.io.StdIn.readInt()
println("Enter a value for n: ")
val n = scala.io.StdIn.readInt()
println(ack(m, n))
}
PartB extends App, but PartC doesn't. Presumably PartA doesn't either.
The App trait can be used to quickly turn objects into executable programs... the whole class body becomes the “main method”.
So PartB defines a main method.

How to convert float to fraction in Swift [duplicate]

I am building a calculator and want it to automatically convert every decimal into a fraction. So if the user calculates an expression for which the answer is "0.333333...", it would return "1/3". For "0.25" it would return "1/4". Using GCD, as found here (Decimal to fraction conversion), I have figured out how to convert any rational, terminating decimal into a decimal, but this does not work on any decimal that repeats (like .333333).
Every other function for this on stack overflow is in Objective-C. But I need a function in my swift app! So a translated version of this (https://stackoverflow.com/a/13430237/5700898) would be nice!
Any ideas or solutions on how to convert a rational or repeating/irrational decimal to a fraction (i.e. convert "0.1764705882..." to 3/17) would be great!
If you want to display the results of calculations as rational numbers
then the only 100% correct solution is to use rational arithmetic throughout all calculations, i.e. all intermediate values are stored as a pair of integers (numerator, denominator), and all additions, multiplications, divisions, etc are done using the rules for rational
numbers.
As soon as a result is assigned to a binary floating point number
such as Double, information is lost. For example,
let x : Double = 7/10
stores in x an approximation of 0.7, because that number cannot
be represented exactly as a Double. From
print(String(format:"%a", x)) // 0x1.6666666666666p-1
one can see that x holds the value
0x16666666666666 * 2^(-53) = 6305039478318694 / 9007199254740992
≈ 0.69999999999999995559107901499373838305
So a correct representation of x as a rational number would be
6305039478318694 / 9007199254740992, but that is of course not what
you expect. What you expect is 7/10, but there is another problem:
let x : Double = 69999999999999996/100000000000000000
assigns exactly the same value to x, it is indistinguishable from
0.7 within the precision of a Double.
So should x be displayed as 7/10 or as 69999999999999996/100000000000000000 ?
As said above, using rational arithmetic would be the perfect solution.
If that is not viable, then you can convert the Double back to
a rational number with a given precision.
(The following is taken from Algorithm for LCM of doubles in Swift.)
Continued Fractions
are an efficient method to create a (finite or infinite) sequence of fractions hn/kn that are arbitrary good approximations to a given real number x,
and here is a possible implementation in Swift:
typealias Rational = (num : Int, den : Int)
func rationalApproximationOf(x0 : Double, withPrecision eps : Double = 1.0E-6) -> Rational {
var x = x0
var a = floor(x)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = floor(x)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
return (h, k)
}
Examples:
rationalApproximationOf(0.333333) // (1, 3)
rationalApproximationOf(0.25) // (1, 4)
rationalApproximationOf(0.1764705882) // (3, 17)
The default precision is 1.0E-6, but you can adjust that to your needs:
rationalApproximationOf(0.142857) // (1, 7)
rationalApproximationOf(0.142857, withPrecision: 1.0E-10) // (142857, 1000000)
rationalApproximationOf(M_PI) // (355, 113)
rationalApproximationOf(M_PI, withPrecision: 1.0E-7) // (103993, 33102)
rationalApproximationOf(M_PI, withPrecision: 1.0E-10) // (312689, 99532)
Swift 3 version:
typealias Rational = (num : Int, den : Int)
func rationalApproximation(of x0 : Double, withPrecision eps : Double = 1.0E-6) -> Rational {
var x = x0
var a = x.rounded(.down)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = x.rounded(.down)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
return (h, k)
}
Examples:
rationalApproximation(of: 0.333333) // (1, 3)
rationalApproximation(of: 0.142857, withPrecision: 1.0E-10) // (142857, 1000000)
Or – as suggested by #brandonscript – with a struct Rational and an initializer:
struct Rational {
let numerator : Int
let denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
init(approximating x0: Double, withPrecision eps: Double = 1.0E-6) {
var x = x0
var a = x.rounded(.down)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = x.rounded(.down)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
self.init(numerator: h, denominator: k)
}
}
Example usage:
print(Rational(approximating: 0.333333))
// Rational(numerator: 1, denominator: 3)
print(Rational(approximating: .pi, withPrecision: 1.0E-7))
// Rational(numerator: 103993, denominator: 33102)
So a little late here, but I had a similar problem and ended up building Swift FractionFormatter. This works because most of the irrational numbers you care about are part of the set of vulgar, or common fractions and are easy to validate proper transformation. The rest may or may not round, but you get very close on any reasonable fraction your user might generate. It is designed to be a drop in replacement for NumberFormatter.
As Martin R said, the Only way to have (99.99%)exact calculations, is to calculate everything with rational numbers, from beginning to the end.
the reason behind the creation of this class was also the fact that i needed to have very accurate calculations, and that was not possible with the swift-provided types. so i created my own type.
here is the code, i'll explain it below.
class Rational {
var alpha = 0
var beta = 0
init(_ a: Int, _ b: Int) {
if (a > 0 && b > 0) || (a < 0 && b < 0) {
simplifier(a,b,"+")
}
else {
simplifier(a,b,"-")
}
}
init(_ double: Double, accuracy: Int = -1) {
exponent(double, accuracy)
}
func exponent(_ double: Double, _ accuracy: Int) {
//Converts a double to a rational number, in which the denominator is of power of 10.
var exp = 1
var double = double
if accuracy != -1 {
double = Double(NSString(format: "%.\(accuracy)f" as NSString, double) as String)!
}
while (double*Double(exp)).remainder(dividingBy: 1) != 0 {
exp *= 10
}
if double > 0 {
simplifier(Int(double*Double(exp)), exp, "+")
}
else {
simplifier(Int(double*Double(exp)), exp, "-")
}
}
func gcd(_ alpha: Int, _ beta: Int) -> Int {
// Calculates 'Greatest Common Divisor'
var inti: [Int] = []
var multi = 1
var a = Swift.min(alpha,beta)
var b = Swift.max(alpha,beta)
for idx in 2...a {
if idx != 1 {
while (a%idx == 0 && b%idx == 0) {
a = a/idx
b = b/idx
inti.append(idx)
}
}
}
inti.map{ multi *= $0 }
return multi
}
func simplifier(_ alpha: Int, _ beta: Int, _ posOrNeg: String) {
//Simplifies nominator and denominator (alpha and beta) so they are 'prime' to one another.
let alpha = alpha > 0 ? alpha : -alpha
let beta = beta > 0 ? beta : -beta
let greatestCommonDivisor = gcd(alpha,beta)
self.alpha = posOrNeg == "+" ? alpha/greatestCommonDivisor : -alpha/greatestCommonDivisor
self.beta = beta/greatestCommonDivisor
}
}
typealias Rnl = Rational
func *(a: Rational, b: Rational) -> Rational {
let aa = a.alpha*b.alpha
let bb = a.beta*b.beta
return Rational(aa, bb)
}
func /(a: Rational, b: Rational) -> Rational {
let aa = a.alpha*b.beta
let bb = a.beta*b.alpha
return Rational(aa, bb)
}
func +(a: Rational, b: Rational) -> Rational {
let aa = a.alpha*b.beta + a.beta*b.alpha
let bb = a.beta*b.beta
return Rational(aa, bb)
}
func -(a: Rational, b: Rational) -> Rational {
let aa = a.alpha*b.beta - a.beta*b.alpha
let bb = a.beta*b.beta
return Rational(aa, bb)
}
extension Rational {
func value() -> Double {
return Double(self.alpha) / Double(self.beta)
}
}
extension Rational {
func rnlValue() -> String {
if self.beta == 1 {
return "\(self.alpha)"
}
else if self.alpha == 0 {
return "0"
}
else {
return "\(self.alpha) / \(self.beta)"
}
}
}
// examples:
let first = Rnl(120,45)
let second = Rnl(36,88)
let third = Rnl(2.33435, accuracy: 2)
let forth = Rnl(2.33435)
print(first.alpha, first.beta, first.value(), first.rnlValue()) // prints 8 3 2.6666666666666665 8 / 3
print((first*second).rnlValue()) // prints 12 / 11
print((first+second).rnlValue()) // prints 203 / 66
print(third.value(), forth.value()) // prints 2.33 2.33435
First of all, we have the class itself. the class can be initialised in two ways:
in the Rational class, alpha ~= nominator & beta ~= denominator
The First way is initialising the class using two integers, first of with is the nominator, and the second one is the denominator. the class gets those two integers, and then reduces them to the least numbers possible. e.g reduces (10,5) to (2,1) or as another example, reduces (144, 60) to (12,5). this way, always the simplest numbers are stored.
this is possible using the gcd (greatest common divisor) function and simplifier function, which are not hard to understand from the code.
the only thing is that the class faces some issues with negative numbers, so it always saves whether the final rational number is negative or positive, and if its negative it makes the nominator negative.
The Second way to initialise the class, is with a double, and with an optional parameter called 'accuracy'. the class gets the double, and also the accuracy of how much numbers after decimal point you need, and converts the double to a nominator/denominator form, in which the denominator is of power of 10. e.g 2.334 will be 2334/1000 or 342.57 will be 34257/100. then tries to simplify the rational numbers using the same method which was explained in the #1 way.
After the class definition, there is type-alias 'Rnl', which you can obviously change it as you wish.
Then there are 4 functions, for the 4 main actions of math: * / + -, which i defined so e.g. you can easily multiply two numbers of type Rational.
After that, there are 2 extensions to Rational type, first of which ('value') gives you the double value of a Rational number, the second one ('rnlValue') gives you the the Rational number in form of a human-readable string: "nominator / denominator"
At last, you can see some examples of how all these work.

Make Int round off to nearest value

I've got two Int values (they have to be Ints) and I want them to round off to the nearest value when in an equation;
var Example = Int()
var secondExample = Int()
Example = (secondExample / 7000)
This equation makes the variable Example always round down to the lowest value. Say for example that the numbers are the following;
var Example = Int()
var secondExample : Int = 20000
Example = (20000 / 7000)
20000 / 7000 equals 2.857... But the variable Example displays 2.
How can I make Example round off to closest number without changing it to a Double
For nonnegative integers, the following function gives
the desired result in pure integer arithmetic :
func divideAndRound(numerator: Int, _ denominator: Int) -> Int {
return (2 * numerator + denominator)/(2 * denominator)
}
Examples:
print(20000.0/7000.0) // 2.85714285714286
print(divideAndRound(20000, 7000)) // 3 (rounded up)
print(10000.0/7000.0) // 1.42857142857143
print(divideAndRound(10000, 7000)) // 1 (rounded down)
The idea is that
a 1 2 * a + b
- + - = ---------
b 2 2 * b
And here is a possible implementation for arbitrarily signed
integers which also does not overflow:
func divideAndRound(num: Int, _ den: Int) -> Int {
return num / den + (num % den) / (den / 2 + den % 2)
}
(Based on #user3441734's updated solution, so we have a reference
cycle between our answers now :)
There is also a ldiv function which computes both quotient
and remainder of a division, so the last function could also be
implemented as
func divideAndRound(num: Int, _ den: Int) -> Int {
let div = ldiv(num, den)
let div2 = ldiv(den, 2)
return div.quot + div.rem / (div2.quot + div2.rem)
}
(I did not test which version is faster.)
see Martin's answer! his idea is great, so i extend his solution for negative numbers
func divideAndRound(n: Int, _ d: Int) -> Int {
let sn = n < 0 ? -1 : 1
let sd = d < 0 ? -1 : 1
let s = sn * sd
let n = n * sn
let d = d * sd
return (2 * n + d)/(2 * d) * s
}
divideAndRound(1, 2) // 1
divideAndRound(1, 3) // 0
divideAndRound(-1, 2) // -1
divideAndRound(-1, 3) // 0
divideAndRound(1, -2) // -1
divideAndRound(1, -3) // 0
the only trouble is that (2 * n + d) can overflow and code will crash.
UPDATE! with help of mathematics for children
func divr(a: Int, _ b: Int)->Int {
return (a % b) * 2 / b + a / b
}
it should work for any Int :-) except 0 denominator.

Scala Branch And Bound Motif Search

Below code searches for a motif (of length 8) in a sequence(String) and, as the result, it has to give back sequence with the best score. The problem is, although the code produces no errors, there is no output at all (probably infinite cycle, I observe blank console).
I am gonna give all my code online and if that is required. In order to reproduce the problem, just pass a number (between 0 and 3 - you can give 4 sequence, so you must choose 1 of them 0 is the first , 1 is the second etc) as args(0) (e.g. "0"), expected output should look something like "Motif = ctgatgta"
import scala.util.control._
object BranchAndBound {
var seq: Array[String] = new Array[String](20)
var startPos: Array[Int] = new Array[Int](20)
var pickup: Array[String] = new Array[String](20)
var bestMotif: Array[Int] = new Array[Int](20)
var ScoreMatrix = Array.ofDim[Int](5, 20)
var i: Int = _
var j: Int = _
var lmer: Int = _
var t: Int = _
def main(args: Array[String]) {
var t1: Long = 0
var t2: Long = 0
t1 = 0
t2 = 0
t1 = System.currentTimeMillis()
val seq0 = Array(
Array(
" >5 regulatory reagions with 69 bp",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaatttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"))
var k: Int = 0
var m: Int = 0
var n: Int = 0
var bestScore: Int = 0
var optScore: Int = 0
var get: Int = 0
var ok1: Boolean = false
var ok3: Boolean = false
ok1 = false
ok3 = false
j = 1
lmer = 8
m = 1
t = 5
n = 69
optScore = 0
bestScore = 0
k = java.lang.Integer.parseInt(args(0))
j = 1
while (j <= t) {
seq(j) = new String()
i = 0
while (i < n) {
seq(j) += seq0(k)(j).charAt(i)
i += 1
}
j += 1
}
j = 1
while (j <= t) {
newPickup(1, j)
j += 1
}
j = 0
bestScore = 0
i = 1
val whilebreaker = new Breaks
whilebreaker.breakable {
while (i > 0) {
if (i < t) {
if (startPos(1) == (n - lmer)) whilebreaker.break
val sc = Score()
optScore = sc + (t - i) * lmer
if (optScore < bestScore) {
ok1 = false
j = i
val whilebreak1 = new Breaks
whilebreak1.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok1 = true
newPickup(0, j)
whilebreak1.break
} else {
ok1 = true
newPickup(1, j)
val whilebreak2 = new Breaks
whilebreak2.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak2.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak1.break
}
}
}
if (ok1 == false) i = 0
} else {
newPickup(1, i + 1)
i += 1
}
} else {
get = Score()
if (get > bestScore) {
bestScore = get
m = 1
while (m <= t) {
bestMotif(m) = startPos(m)
m += 1
}
}
ok3 = false
j = t
val whilebreak3 = new Breaks
whilebreak3.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok3 = true
newPickup(0, j)
whilebreak3.break
} else {
ok3 = true
newPickup(1, j)
val whilebreak4 = new Breaks
whilebreak4.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak4.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak3.break
}
}
}
if (ok3 == false) i = 0
}
}
}
println("Motiv: " + Consensus())
// println()
j = 1
while (j <= t) {
t2 = System.currentTimeMillis()
j += 1
}
println("time= " + (t2 - t1) + " ms")
}
def Score(): Int = {
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var sum: Int = 0
sum = 0
max = 0
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
j = 1
while (j <= lmer) {
max = 0
m = 1
while (m <= 4) {
if (ScoreMatrix(m)(j) > max) {
max = ScoreMatrix(m)(j)
}
m += 1
}
sum += max
j += 1
}
sum
}
def Consensus(): String = {
var i: Int = 0
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var imax: Int = 0
var str: String = null
i = 1
while (i <= t) {
pickup(i) = " " +
seq(i).substring(bestMotif(i), bestMotif(i) + lmer)
i += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= t) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
str = ""
imax = 0
j = 1
while (j <= lmer) {
max = 0
i = 1
while (i <= 4) {
if (ScoreMatrix(i)(j) > max) {
max = ScoreMatrix(i)(j)
imax = i
}
i += 1
}
imax match {
case 1 => str += 'a'
case 2 => str += 'c'
case 3 => str += 'g'
case 4 => str += 't'
}
j += 1
}
str
}
def newPickup(one: Int, h: Int) {
if (one == 1) startPos(h) = 1 else startPos(h) += 1
pickup(h) = " " + seq(h).substring(startPos(h), startPos(h) + lmer)
}
}
and thanks, i hope someone gonna find my failure.
Your current implementation 'hangs' on this loop:
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
As it stands, the exit condition is never fulfilled because the relation between k and i never changes. Either increment k or decrement i.
It looks like programming is not the key aspect of this work, but increased modularity should help contain complexity.
Also, I wonder about the choice of using Scala. There're many areas in this algorithm that would benefit of a more functional approach. In this translation, using Scala in an imperative way gets cumbersome. If you have the opportunity, I'd recommend you to explore a more functional approach to solve this problem.
A tip: The intellij debugger didn't have issues with this code.