How can I add the calories calculated from custom formula in a workout in HealthApp from Apple Watch.

I am creating a workout session in Apple Watch. I am tracking the distance and the heart rate through the workout session. The HKLiveWorkoutBuilder is already set. The data collects correctly. But I calculate calories from my own equation. But when I finish the workout, the calories are not saved correctly. For eg. if I have calories from my formula equals to 20kCal, in HealthApp, it Shows a different number.
Code Block
func endWorkout(caloriesCalc: Double, completion: @escaping (_ success: Bool, _ error: String?) -> Void) {
        session.end()
        if let quantityType = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned) {
            let unit = HKUnit.largeCalorie()//HKUnit.kilocalorie()
            let caloriesBurned = caloriesCalc
            let quantity = HKQuantity(unit: unit, doubleValue: caloriesBurned)
            
            let sample = HKQuantitySample(type: quantityType, quantity: quantity, start: self.workoutStartTime, end: Date())//HKCumulativeQuantitySample(type: quantityType, quantity: quantity, start: self.workoutStartTime, end: Date(), metadata: nil)
            builder.add([sample]) { (success, error) in
                guard success else {
                    print("error ======> \(error)")
                    return
                }
                self.builder.endCollection(withEnd: Date()) { (success, error) in
                    guard success else {
                        completion(success, "Something went wrong! Please try again.")
                        return
                    }
                    self.activeSession = nil
                    self.builder.finishWorkout { (workout, error) in
                        if let error = error {
                            completion(false, "Something went wrong! Please try again.")
                            return
                        }
                        self.activityType = nil
                        completion(true, nil)
                    }
                }
            }
        }
    }


What number are you getting? Note that the final computation of active energy (and other types) for the HKWorkout sample takes into account the actual workout duration, including pauses; since you're creating a single large active energy sample spanning a duration from the beginning of the workout until the call to endWorkout it's possible that you're creating a sample that doesn't properly account for workout start/end time or pause/resume periods.
How can I add the calories calculated from custom formula in a workout in HealthApp from Apple Watch.
 
 
Q